注释相关过滤对象的计数
Annotate count of related related filtered objects
我有这些型号:
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)))
我有这些型号:
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)))