In Django QuerySet, how do I check for a specific object in a ManyToMany field?

django, django-models

Solution

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')

Problem

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?

Original source