查询ForeignKey的Django对象列表

时间:2017-02-22 22:19:46

标签: python django django-models django-templates django-views

我有MenuSection模型和Product模型。 Product模型将MenuSection设置为ForeignKey。一切正常,除了我很难弄清楚如何查询Product模型并列出ForeignKey特有的对象列表,但是在模板顶部打印一次ForeignKey值。

我希望产品打印到模板的示例:

Salads (FK) <= Only printed once 
   Cobb (product.name)
   Ceasar (product.name)
Pizza (FK)
   Supreme (product.name)
   Veggie (product.name)
...

代码

@register.inclusion_tag('tags/_starters.html', takes_context=True)
def products(context):
    product = Product.objects.all()
    return {
        'product': product,
        'request': context['request'],
    }

标记模板

{% for p in product %}
  <div class="menu-wrapper">
    <div class="menu-description">
    <h1>{{ p.section.name }}</h1> <======= This is the (FK) that I need to print once.
      <div class="menu-list">
        <h5>{{ p.name }}</h5>

        <p class="price">
          {% if p.price_b %}
            {{ p.price_a }}/
            {{ p.price_b }}
          {% else %}
            {{ p.price_a }}
          {% endif %}
        </p>

        <span class="menu-dot-line"></span>
      </div>
      <p class="menu-ingredients">{{ p.description }}</p>
    </div>
  </div>
{% endfor %}

模型

@register_snippet
class Product(ClusterableModel):
    section = models.ForeignKey(MenuSection, verbose_name='Menu Section')
    name = models.CharField(max_length=255, verbose_name='Menu Item Name')
...

1 个答案:

答案 0 :(得分:1)

不要在标记中查询Product,而是返回

return {
    'menu_sections': MenuSection.objects.all()
}

然后,在您的模板中

{% for menu_section in menu_sections %}
    {{ menu_section.name }}
    {% for product in menu_section.product_set.all %}
        {{ product.name }}
    {% endfor %}
{% endfor %}