Getting values ​​from two different tables using Django QuerySet

For the following models:

class Topping(models.Model):
    name = models.CharField(max_length=100)

class Pizza(models.Model):
    name = models.CharField(max_length=100)
    toppings = models.ManyToManyField(Toppping)

My data is as follows:

Pizza tables and countertops are connected:

ID  NAME        TOPPINGS
------------------------------------
1   deluxe      topping_1, topping_2
2   deluxe      topping_3, topping_4
3   hawaiian    topping_1

I want to get the pizza id along with my corresponding toppings for the whole pizza with the name deluxe. My expected result:

1   topping_1
1   topping_2
2   topping_3
2   topping_4

Connection table:

pizza_toppings
--------------
id    
pizza_id    
topping_id

Here is the SQL equivalent that I want to achieve:

SELECT p.id, t.name
FROM pizza_toppings AS pt
INNER JOIN pizza AS p ON p.id = pt.pizza_id
INNER JOIN topping AS t ON t.id = pt.topping_id
WHERE p.name = 'deluxe'    

Any ideas on what the matching Jango Queryset looks like? I also want to sort the resulting fillings by name, if the above is not complicated enough.

+3
source share
2 answers

, , . select_related, . , :

result = []
pizzas = Pizza.objects.select_related().filter(name='deluxe')
for pizza in pizzas:
    for toppings in pizza.toppings.all():
        result.append((pizza.pk, topping.name))

:

[
    (1, topping_1),
    (1, topping_2),
    (2, topping_3),
    (2, topping_4),
]

, , , , , .

+2

, .

pizzas = topping.pizza_set.all()

, , ( , "deluxe" )

pizza = topping.pizza_set.get(name="deluxe")

, . ( ):

toppings = {}
pizzas = Pizza.objects.filter(name="deluxe")
for pizza in pizzas:
    for topping in pizza.toppings.all():
        toppings[topping.name] = pizza.name
sorted_toppings = toppings.keys()
sorted_toppings.sort()

.

0

Source: https://habr.com/ru/post/1717878/


All Articles