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

前端 未结 3 1162
遇见更好的自我
遇见更好的自我 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 20:59

    In Django 1.8 I believe this can be achieved with conditional aggregation . However for previous versions I would do it with .extra

    ModelA.objects.extra(select={
        'account_count': 'SELECT COUNT(*) FROM account WHERE modela.account_id = account.id AND account.some_prop IS NOT NULL'
    })
    

提交回复
热议问题