views:

178

answers:

1

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?

+7  A: 

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