【问题标题】:Duplicate query for every form in the formset对表单集中的每个表单进行重复查询
【发布时间】:2016-06-30 13:07:48
【问题描述】:

在我的 django 应用程序中,我的用户可以拥有多个职位。即:Position 模型具有 User 模型的外键。通过使用 django modelformset_factory,我输出与当前登录用户相关的所有职位,如下所示:

Views.py:

class ABCUpdate(View):

    def get(self, request):
        user = request.user
        PositionFormSet = modelformset_factory(Position)
        formset = PositionFormSet(queryset=user.position_set.all().prefetch_related('symbol'))
        return render(request,
                      'some_template.html',
                      {'formset': formset})

some_template.html

<form action="#" method="post">
  {% csrf_token %}
  {{ formset.management_form }}
  {% for position in formset %}
    <div class="row">
      {{ position }}
    </div>
  {% endfor %}
  <button type="submit">
    Update
  </button>
</form>

定位模型:

class Position(models.Model):

    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    symbol = models.OneToOneField(Symbol)
    # more fields...

some_template.html 上的字段之一是symbol 字段(即:我在上面的 sn-ps 中使用prefetch_related 的字段)。 Symbol 来自使用外键的不同模型。这意味着在 html 模板上,symbol 字段是一个下拉列表,允许用户选择所需的符号。

这一切都正常工作,但问题是正在查询数据库以获取表单集中的每个表单以检索symbol 的列表。例如,如果用户有 10 个仓位,那么每个仓位都会有一个符号下拉列表,...这会导致一个单独的数据库查询来检索所有符号。

如何对所有可用的symbol 进行一次查询,并将其用于表单集中每个表单的下拉列表?

【问题讨论】:

  • 有点不清楚:从PositionSymbol 是否有FK,反之亦然?
  • 是的,外键是从位置到符号。换句话说,一个用户可以有多个职位。然后对于每个位置,他们将选择一个符号,该符号来自符号表/模型。
  • 为了清楚起见,我已将部分职位模型添加到原始帖子中
  • @MuhammadTahir 是的,您提到的帖子与我遇到的问题相同。但是,如果您通读该帖子和 cmets,则该解决方案不起作用。我也试过了,还是不行。

标签: python django


【解决方案1】:

我认为您应该指向 prefetch_related 模型位置的所有字段,这些字段具有指向另一个模型的链接,在您的情况下,您必须添加字段用户: PositionFormSet(queryset=user.position_set.all().prefetch_related('symbol', 'user'))


附:它对我有用。

【讨论】:

    猜你喜欢
    • 2020-04-16
    • 2011-12-08
    • 1970-01-01
    • 2016-03-05
    • 1970-01-01
    • 2011-01-15
    • 2017-04-27
    • 2013-04-05
    • 1970-01-01
    相关资源
    最近更新 更多