【问题标题】:Query Django Object Lists of ForeignKey查询 ForeignKey 的 Django 对象列表
【发布时间】:2017-02-22 22:19:46
【问题描述】:

我有一个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')
...

【问题讨论】:

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


    【解决方案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 %}
    

    【讨论】:

    • 这太棒了!!
    猜你喜欢
    • 1970-01-01
    • 2016-05-27
    • 1970-01-01
    • 2021-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-17
    • 2012-12-31
    相关资源
    最近更新 更多