Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throwing ZeroDivisionError

I need to get a calculation of some data so, in annotate I put some maths logic with other field but whenever there is 0 it is throwing an error. I need to handle that error in annotate. My code looks like this:

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

In total_billable, there is total_billable_leads variable which may have Zero(0) then on a division it will throw an error. So, please help me to handle this exception in annotate.

CampaignContactHistory Model

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)

For result I want if it is an error or zero(0) it should return zero(0) otherwise the calculated value.

like image 842
Shubham Srivastava Avatar asked May 30 '18 08:05

Shubham Srivastava


1 Answers

the total_amount and total_billable_leads are constants so you get the error on python level, so the solution is:

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))),
            #               ^^^^^^^^^^^^^^^
        )
like image 160
Brown Bear Avatar answered Oct 13 '22 00:10

Brown Bear