django annotate and count: how to filter the ones to include in count

前端 未结 3 1122
遇见更好的自我
遇见更好的自我 2021-01-31 20:03

Given a queryset, I add the count of related objects (ModelA) with the following:

qs = User.objets.all()
qs.annotate(modela__count=models.Count(\'modela\'))
         


        
3条回答
  •  鱼传尺愫
    2021-01-31 21:03

    You can simply filter before you annotate:

    from django.db.models import Q, Count
    
    qs = ModelA.objects.filter(account__prop1__isnull=False).annotate(account_count=Count('account'))
    

提交回复
热议问题