V
V
Vampre2018-08-02 02:15:43
Django
Vampre, 2018-08-02 02:15:43

How to output many to many fields in django template?

From the Django documentation

from django.db import models

class Topping(models.Model):
    # ...
    pass

class Pizza(models.Model):
    # ...
    toppings = models.ManyToManyField(Topping)

How to display all pizzas with their toppings is clear:
pizzas = Pizza.objects.all()
And in the template:
{% for pizza in pizzas %}
    В пиццу {{ pizza.name }} входят топпинги:
    {% for topping in pizzas.toppings.all %}
    {{ topping.name }}
    {% endfor %}
{% endfor %}

And if, for example, you need to display a list of toppings and indicate for each topping in which pizza it is used? After all, you can’t do it in the toppings.pizzas.all template, because the m2m connection is specified in only one model ...
Manually form a list like [{'pizza': pizza, 'toppings': [topping1, topping2,...]} in the view , ...] ?
PS: I'm not interested in how to make a query to the database (find pizzas through toppings), but how to display it in the template so that in the end it turns out like this:
Tomato topping is used in pizzas: 1. Italian, 2. Meat;
Corn topping is used in pizzas: 1. Meat, 2. Chicken

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Animkim, 2018-08-02
@Animkim

topping.pizza_set.all() or set your own related_name.

toppings = models.ManyToManyField(Topping, related_name='pizza')
---
topping.pizza.all()

T
Tim, 2018-08-02
@darqsat

I did something similar through
Kuri 's annotations and aggregations https://docs.djangoproject.com/en/2.0/topics/db/ag...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question