【问题标题】:Django Queryset - Get counts by model.choicesDjango Queryset - 通过 model.choices 获取计数
【发布时间】:2021-09-21 03:44:16
【问题描述】:

我有以下模型,其中包含有关客户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, 
 ...
} 

【问题讨论】:

    标签: django django-models count django-queryset


    【解决方案1】:

    试试这个:

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

    这将返回如下内容:

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

    【讨论】:

    • 非常有趣的解决方案,我试图找出一个这样的解决方案......
    • 一击数据库:)
    • 最少 DB 命中率始终是优先级 :)
    【解决方案2】:

    我认为您可以使用 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)
    

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

    【讨论】:

      【解决方案3】:

      你会得到这样的计数:

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

      【讨论】:

        猜你喜欢
        • 2018-06-04
        • 2020-11-15
        • 1970-01-01
        • 1970-01-01
        • 2020-11-29
        • 1970-01-01
        • 2021-11-20
        • 1970-01-01
        • 2019-03-25
        相关资源
        最近更新 更多