python - 构建组合相关字段列表的最有效方法

标签 python django django-templates

我有两个模型:VendorProductVendor 模型有一个 state 字段。我想创建一个页面,列出特定州的供应商,并按产品分组。示例输出为:

Vendors in Maryland

  • Product A
    • Vendor 1
  • Product B
    • Vendor 2
    • Vendor 3
  • Product C
    • Vendor 4
    • Vendor 5

供应商Product作为ForeignKey。我可以按州名称搜索供应商。

def vendor_by_state_page(request, state_name):
    vendors = Vendor.objects.filter(state=state_name)
    products = Products.objects.all()

我可以在模板中进行嵌套循环,但这似乎效率低下:

{% for product in products %}
  <h2>{{product.name}}</h2>
  {% for vendor in vendors %}
    {% if vendor.product == product %}
       - {{vendor.display_name}}
    {% endif %}
  {% empty %}
    No {{product.name}} vendors in {{state.name}}.
  {% endfor %}
{% endfor %}

另外,空在这里实际上不起作用,因为有结果,它们只是与 if 不匹配。理想情况下,我根本不希望该产品出现在列表中。

所以,希望这已经足够了。我确信我错过了一些东西。任何帮助都是极好的。谢谢!

最佳答案

您需要使用预取来过滤相关集。

    from django.db.models import Prefetch
    products = Products.objects.prefetch_related(Prefetch(
        'vendor_set',
        queryset=Vendor.objects.filter(
            state=state_name
        )
    ))

在模板中只需迭代:

{% for product in products %}
  <h2>{{product.name}}</h2>
  {% for vendor in product.vendor_set.all %}
   - {{vendor.display_name}}
  {% empty %}
   No {{product.name}} vendors in {{state.name}}.
  {% endfor %} 
{% endfor %}

关于python - 构建组合相关字段列表的最有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35008250/

相关文章:

python - 让 setuptools 忽略 PyPI 存储库

javascript - 如何将 javascript 函数的值传递给 Django View ?

python - unicorn "configuration cannot be imported"

django - 在 Django 中将数据从数据库传递到 highcharts

python - 向新用户 App Engine 显示新消息

javascript - 以正确的方式使用javascript将动态表单添加到django formset

python - CharField 最大长度 2^n 与 2^n-1

python - 如何在请求调用中添加持久 header ?

python - Django formset 为多张图片上传创建多个输入

python - 如何在 django 模板中使用换行符从数据库中输出文本?