简体   繁体   中英

Django filter by group count

For a model eg 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.

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

Have you tried something like that:

from django.db.models import Count

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM