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

I have the following models:

class Topping(models.Model):
    ...

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

      

Then I have the top object:

cheese = Topping.objects.get(name='cheese')

      

Then I find all the cheese pizzas filling the following query:

Pizza.objects.all().filter(toppings=cheese)

      

The above seems to work, but is it the right thing to do?

+2


source to share


1 answer


Yes, although all () are redundant.

Or, to avoid the extra request to get the cheese object, you can use the standard double underscore syntax to traverse the relationship:



Pizza.objects.filter(toppings__name='cheese')

      

+9


source







All Articles