gpt4 book ai didi

python - 抛出 ZeroDivisionError

转载 作者:太空狗 更新时间:2023-10-30 00:04:46 24 4
gpt4 key购买 nike

我需要对一些数据进行计算,所以在注释中我将一些数学逻辑与其他字段放在一起,但只要有 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))),
)

在 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)

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

最佳答案

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))),
# ^^^^^^^^^^^^^^^
)

关于python - 抛出 ZeroDivisionError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50599454/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com