0

My problem is that when my Database is empty I am getting this error

IndexError at / list index out of range

>  period = Period.objects.all()
>     try:
>         period_current = [obj for obj in period if ((obj.is_current)==True)]
>                     total_payment_period_current_dict = LeasePayment.objects.filter(payment_date__range=[period_current[0].start_date,
> period_current[0].end_date]).aggregate(Sum('amount')) ...
>         total_payment_period_current = total_payment_period_current_dict['amount__sum']
>     except ValueError:
>         raise Http404("Can't perform calculation for total_payment_period_current, check data ")

I hoped I can handle it with exeption to give meaningful error , but it doesn't work. What I can do to give meaningful error . Or ideally to avoid this exception all together in case of empty tables?

1 Answer 1

1

If you want to handle this error then I would suggest putting a check for length of list.

try:
    period_current = [obj for obj in period if ((obj.is_current)==True)]
    if len(period_current == 0) {
       raise Http404("Can't perform calculation for total_payment_period_current, check data ") 
    }
    total_payment_period_current_dict = LeasePayment.objects.filter(payment_date__range=
                                  [period_current[0].start_date,
                period_current[0].end_date]).aggregate(Sum('amount')) 
         total_payment_period_current = total_payment_period_current_dict['amount__sum']
     except ValueError:
         raise Http404("Can't perform calculation for total_payment_period_current, check data ")

This is a wrong exception for your case. You might want to use IndexError exception instead of ValueError exception.

except IndexError:
    raise Http404("Can't perform calculation for" +
                  "total_payment_period_current, check data ")

This answer might be helpful to you to understand the problem.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.