0

Ich habe ein MenuSection Modell und ein Modell. Das Produktmodell hat MenuSection als ForeignKey festgelegt. Alles funktioniert gut, außer dass ich Schwierigkeiten habe herauszufinden, wie man das Produktmodell abfragt und eine Liste von Objekten auflistet, die für ForeignKey spezifisch sind, aber den ForeignKey-Wert einmal oben in der Vorlage ausdrücke.Django Objektlisten von ForeignKey abfragen

Beispiel dafür, wie ich die Produkte Druck auf die Vorlage möchten:

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 Vorlage

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

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

Antwort

1

Statt Product in Ihrem Tag abfragt, Rückkehr

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

Dann in Ihrer Vorlage

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

Das ist brilliant !! –

Verwandte Themen