注释计数相关的相关过滤对象

问题描述

我有以下模型:

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

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

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

我需要注释每个类别的有效产品数量

基本上是这样:

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

我尝试过:

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

这将引发错误。你知道怎么注释吗?

解决方法

filter应该是Count对象的参数:

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