Django 获取具有值的相关对象的数量并将其添加到注释中
Django get count of related objects with value and add it to an annotation
如果我想为每个父对象注释相关对象的数量,我会这样做:
Agent.objects.annotate(deal_count=Count('deal'))
如果我的 Deal
对象有一个 closed
布尔值,我将如何注释标记为关闭的交易数量?
您可以使用 filter=…
parameter [Django-doc]:
from django.db.models import Q
Agent.objects.annotate(deal_count=Count('deal', <strong>filter=Q(deal__closed=True)</strong>))
或者如果您想用两个计数进行注释:
from django.db.models import Q
Agent.objects.annotate(
deal_count=Count('deal'),
closed_deal_count=Count('deal', <strong>filter=Q(deal__closed=True)</strong>)
)
如果我想为每个父对象注释相关对象的数量,我会这样做:
Agent.objects.annotate(deal_count=Count('deal'))
如果我的 Deal
对象有一个 closed
布尔值,我将如何注释标记为关闭的交易数量?
您可以使用 filter=…
parameter [Django-doc]:
from django.db.models import Q
Agent.objects.annotate(deal_count=Count('deal', <strong>filter=Q(deal__closed=True)</strong>))
或者如果您想用两个计数进行注释:
from django.db.models import Q
Agent.objects.annotate(
deal_count=Count('deal'),
closed_deal_count=Count('deal', <strong>filter=Q(deal__closed=True)</strong>)
)