Django 查询集 - 按 model.choices 获取计数

Django Queryset - Get counts by model.choices

我有以下模型,其中包含有关客户 Leads 的所有详细信息。客户想查看他的 Leads 跟进状态。

class FollowUp(models.Model):
    CALL_CHOICES = [("0", "Call Unanswered"),
                  ("1", "Call Later"),
                  ("2", "Visit Scheduled"),
                  ("3", "Not Visited"),
                  ("4", "Not reachable"),
                  ("5", "Wrong Number"),
                  ("6", "Not Interested"),
                  ("7", "Deal Closed")]
    status = models.CharField(_("Call Status"),
            max_length = 20,
            choices = CALL_CHOICES,
            default = '1'
        )
    next_action_on = DateTimeField(_("Next Action"), auto_now_add=False, 
                null=True, blank=True)
    reminder = models.BooleanField(_("reminder"), default=False)  
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)

class Lead(models.Model):
    followups = models.ManyToManyField(FollowUp, verbose_name=_("Follow up"), blank=True)
    ...

如何获得每个 status 选择的 Lead 计数。比如

{
 'Call Unanswered': 12 #Leads, 
 'Call Later': 10 # Leads  
 'Visit Scheduled': 20, #Leads, 
 ...
} 

你会得到这样的计数:

>>> Leads.objects.filter(follow_up__status=0).count()
>>> 10

我认为您可以使用 for 迭代器遍历 CALL_CHOICES 并根据状态过滤行。

queryset = Leads.objects.all()
res = {}
for i in FollowUp.CALL_CHOICES:
    res[i[1]] = queryset.filter(followups__status=i[0]).aggregate(total=Count('pk'))['total']
print(res)

在脚本结束时,您将获得每对值。

试试这个:

Lead.objects.aggregate(
    **{
        choice[1]: Count(
            'followups', filter=Q(followups__status=choice[0])
        ) for choice in Followup.CALL_CHOICES
    }
)

这会 return 类似于:

{'Call Unanswered': 0,
 'Call Later': 0,
 'Visit Scheduled': 0,
 'Not Visited': 0,
 'Not reachable': 0,
 'Wrong Number': 0,
 'Not Interested': 0,
 'Deal Closed': 0}