抛出ZeroDivisionError

Shu*_*ava 6 python django annotations django-models django-orm

我需要计算一些数据,因此,在注释中我将一些数学逻辑与其他字段放在一起,但只要有0就会抛出错误.我需要在注释中处理该错误.我的代码看起来像这样:

total_amount = Invoice.objects.filter(client_account__account_UID=account_UID,
                                              created_at__range=(from_date, to_date)
                                              ).aggregate(Sum('total_amount'))['total_amount__sum']

total_billable_leads = CampaignContact.objects.filter(campaign=campaigns, billable=True, billable_item__created_at__range=(from_date, to_date)).count()

cch = CampaignContactHistory.objects.annotate(
            campaign_name=F('campaign__name')
                 ).values('campaign_name'
                 ).filter(id__in=cch_ids
                 ).annotate(
            total=Count('lead_status'),
            scheduled=Count(Case(When(lead_status='10', then=1))),
            total_billable=(int(total_amount) / total_billable_leads) * Count(Case(When(campaign_contact__billable=True, then=1))),
        )
Run Code Online (Sandbox Code Playgroud)

在total_billable中,有一个total_billable_leads变量可能有零(0)然后在一个除法它会抛出一个错误.所以,请帮我在注释中处理这个异常.

CampaignContactHistory模型

class CampaignContactHistory(DateAwareModel):
    campaign_contact = models.ForeignKey(CampaignContact, on_delete=models.CASCADE)
    lead_status = models.CharField(max_length=20, choices=leadstatus, default=FRESH)
    campaigner = models.ForeignKey(Resource, on_delete=models.CASCADE)
    response_date = models.DateTimeField(null=True, blank=True)
    first_reponse = models.TextField(blank=True, null=True, default='')
    second_reponse = models.TextField(blank=True, null=True, default='')
    campaign = models.ForeignKey(Campaign, null=True, blank=True)
Run Code Online (Sandbox Code Playgroud)

对于结果我想要如果它是一个错误或零(0)它应该返回零(0)否则计算的值.

小智 4

和是常量total_amounttotal_billable_leads因此您会在 python 级别上得到错误,因此解决方案是:

if total_billable_leads:
    total_amount_avg = int(total_amount) / total_billable_leads
else:
    total_amount_avg = 0

cch = CampaignContactHistory.objects.annotate(
            campaign_name=F('campaign__name')
                 ).values('campaign_name'
                 ).filter(id__in=cch_ids
                 ).annotate(
            total=Count('lead_status'),
            scheduled=Count(Case(When(lead_status='10', then=1))),
            total_billable=total_amount_avg * Count(Case(When(campaign_contact__billable=True, then=1))),
            #               ^^^^^^^^^^^^^^^
        )
Run Code Online (Sandbox Code Playgroud)

  • 有时会发生),很高兴为您提供帮助! (2认同)