Search code examples
djangodjango-querysetdjango-databasedjango-aggregationdjango-annotate

Annotate count of related related filtered objects


I have these models:

class Shop(..):
    category = ForeignKey...

class Product(..):
    shop = ForeignKey...
    category = ForeignKey...
    is_active = BooleanField...

class Category(..):
    name = ...

I need to annotate the number of active products for each category.

Basically this:

for cat in Category.objects.all():
    count = Product.objects.filter(shop__category=cat)

I tried:

Category.objects.annotate(product_count=Count('shop__products'),filter=Q(shop__products__is_active=True))

django.core.exceptions.FieldError: Related Field got invalid lookup: is_active

This raises an error. Do you know how to annotate this?


Solution

  • filter should be argument of Count object:

    Category.objects.annotate(product_count=Count('shop__products', filter=Q(shop__products__is_active=True)))