0
votes

For a model e.g. Pizza that has a to many relationship with a model Topping How can I query for all Pizzas with only 2 Toppings?

I previously iterated over the Pizzas and made a separate query for the Toppings count and only added the one with 2 to my list. But I am running into a performance problem.

2

2 Answers

2
votes

You can filter by annotations (described at https://docs.djangoproject.com/en/dev/topics/db/aggregation/#filtering-on-annotations)

doubles = ( Pizza
     .objects
     .annotate(num_toppings=Count('toppings'))
     .filter(num_toppings=2)
    )
0
votes

Have you tried something like that:

from django.db.models import Count

Pizzas.objects.annotate(tc=Count('toppings')).filter(tc=1)