Home > Software design >  How to avoid list index out of range in Django ORM query
How to avoid list index out of range in Django ORM query

Time:01-05

I have a tricky scenario here ,usually I get 6 values from the below query , basically prices at start and month end of the month, prices value will be there every time

trade_date price
01-01-2021 120.2
31-01-2021 220.2
01-02-2021 516.2
28-02-2021 751.0
01-03-2021 450.2
31-03-2021 854.9

and I need Sum of 1st month starting price 1st month Ending price every months ending price ie 120.2 220.2 751.0 854.9 but in some cases, last month data tend to miss, how to handle those scenarios

monthly_values = Items.objects.filter(trade_date__gte=quarter_start_date,
                          trade_date__lte=quarter_end_date).values_list('price',
                          flat=True).order_by('trade_date')
 
total_sum = monthly_values[0] monthly_values[1] monthly_values[3] monthly_values[5])

Currently getting list index out of range from the above because of missing values

CodePudding user response:

I think you're using columns instead of index. Does this work?

total_sum = 0
for i in [0, 1, 3, 5]:    
    total_sum  = monthly_values.iat[i].iat[0]

CodePudding user response:

Can you try this?

     total_values = sum(monthly_values[i] 
                        for i in range(len(monhtly_values))
                        if monthly_values[i])
  •  Tags:  
  • Related