python - 抛出 ZeroDivisionError
问题描述
我需要计算一些数据,所以在注释中我将一些数学逻辑与其他字段一起放置,但只要有 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),然后在除法上会抛出错误。所以,请帮助我在注释中处理这个异常。
活动联系历史模型
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_amount
and是常量,total_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))),
# ^^^^^^^^^^^^^^^
)
推荐阅读
- javascript - 从他们有子的常量中获取随机元素
- elasticsearch - Elasticsearch 上的桶数
- r - 用于 Power BI 的 R 到 JSON 中的嵌套列表
- .net - 什么是毛伊?MAUI 和 Xamarin 有什么区别
- akka.net - 正确处理 Akka 异步延续中的异常
- javascript - 如何将 Fused Location API 与电容器一起使用?- 离子 5
- python - Scrapy:无法正确抓取嵌套链接 - 所有记录都重复
- python - Keras Tensorfolow 的 BatchNormalization 层中的属性“可训练”和“训练”有什么区别?
- php - Laravel“类名必须是有效的对象或字符串”
- ios - 影响其他视图的 SwiftUI 动画