Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Django QuerySet, how do 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)

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?

like image 250
Thierry Lam Avatar asked Dec 30 '25 19:12

Thierry Lam


1 Answers

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')
like image 163
Daniel Roseman Avatar answered Jan 02 '26 10:01

Daniel Roseman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!