I have the following models:
class Topping(models.Model):
...
class Pizza(models.Model):
toppings = models.ManyToManyField(Topping)
I then have a topping object:
cheese = Topping.objects.get(name='cheese')
I then find all pizzas with the cheese topping with the following query:
Pizza.objects.all().filter(toppings=cheese)
The above seems to be working but is it the right way to do it?
Yes, although the all() is superfluous.
Or, to avoid the extra query to get the cheese object, you can use the standard double-underscore syntax to traverse relations:
Pizza.objects.filter(toppings__name='cheese')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With