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 looks like the following:
Pizza and Topping tables joined:
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 their corresponding toppings for all pizza named deluxe
. My expected result is:
1 topping_1
1 topping_2
2 topping_3
2 topping_4
The junction table is:
pizza_toppings
--------------
id
pizza_id
topping_id
Here's the SQL equivalent of what 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 corresponding Django Queryset looks like? I also want to sort the resulting toppings by name if the above is not challenging enough.