Charles Smith
Charles Smith

Reputation: 3289

Query Django Object Lists of ForeignKey

I have a MenuSection model and a Product model. The Product model has MenuSection set as a ForeignKey. Everything works fine, except I am having difficulty figuring out how to query the Product model and listing out a list of objects unique to the ForeignKey, but print the ForeignKey value once at the top of the template.

Example of how I would like the Products printing to the template:

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

Tag

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

Tag Template

{% 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 %}

Model

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

Upvotes: 0

Views: 55

Answers (1)

SMX
SMX

Reputation: 1442

Instead of querying Product in your tag, return

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

Then, in your template,

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

Upvotes: 1

Related Questions