-1

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?

Milano
  • 18,048
  • 37
  • 153
  • 353
  • What erro you have got? – JPG Sep 04 '20 at 13:45
  • @ArakkalAbu django.core.exceptions.FieldError: Related Field got invalid lookup: is_active – Milano Sep 04 '20 at 13:46
  • BTW, from your post, it is not clear how does the `Shop` and `Product` is related. IMHO, better to add the *"relevant, exact model specification"* in questions so that you will have a high chance of getting accurate answers. – JPG Sep 04 '20 at 13:55

1 Answers1

3

filter should be argument of Count object:

Category.objects.annotate(product_count=Count('shop__products', filter=Q(shop__products__is_active=True)))
neverwalkaloner
  • 46,181
  • 7
  • 92
  • 100