【问题标题】:Throwing ZeroDivisionError抛出 ZeroDivisionError
【发布时间】:2018-11-09 00:00:23
【问题描述】:

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

【问题讨论】:

  • 你想要什么结果?删除此记录还是可以除以 1?
  • 如果它是零(0)或错误,那么它应该只返回零
  • 请添加模型和一些行来创建实例
  • CampaignContactHistory你想要这个型号?
  • 是的,我的意思是CampaignContactHistory

标签: python django django-models annotations django-orm


【解决方案1】:

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

【讨论】:

  • 你的total_amount是什么?常数
  • 它是来自单独查询的整数
  • 哦……!!多么简单的逻辑……怎么能错过……!!非常感谢..... :)
  • 有时会发生),很高兴为您提供帮助!
猜你喜欢
  • 2021-08-25
  • 1970-01-01
  • 1970-01-01
  • 2023-03-06
  • 2016-05-16
  • 1970-01-01
  • 2022-11-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多