如何避免 Django ORM 查询中的列表索引超出范围
How to avoid list index out of range in Django ORM query
我这里有一个棘手的场景,通常我从下面的查询中得到 6 个值,基本上是月初和月末的价格,每次都会有价格值
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
我需要第 1 个月的起始价格 + 第 1 个月的结束价格 + 每个月的结束价格的总和
即120.2+220.2+751.0+854.9
但在某些情况下,上个月的数据容易遗漏,如何处理这些情况
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])
由于缺少值,当前正在获取超出上述范围的列表索引
您需要访问行,然后是列:
total_sum = 0
for i in [0, 1, 3, 5]:
total_sum += monthly_values[i][1]
这使您可以“手动”访问。 @Asger 的回答是自动的。
所以我上次使用 DjangoORM 已经有一段时间了,但是你可以做类似的事情
from datetime import date
monthly_values: list[tuple[date, float]] = Items.objects.filter(trade_date__gte=quarter_start_date,
trade_date__lte=quarter_end_date).values_list('trade_date', 'price').order_by('trade_date')
然后创建一个函数,将我们输入的起始价格添加到结果中,然后添加不是该月第一天的所有价格。
def get_prices(month_and_prices: list[tuple[date, float]]) -> float:
res = month_and_prices[0][1]
res += sum([x[1] for x in month_and_prices[1:] if x[0].day > 1])
return res
这应该可以解决您的问题
我这里有一个棘手的场景,通常我从下面的查询中得到 6 个值,基本上是月初和月末的价格,每次都会有价格值
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
我需要第 1 个月的起始价格 + 第 1 个月的结束价格 + 每个月的结束价格的总和 即120.2+220.2+751.0+854.9 但在某些情况下,上个月的数据容易遗漏,如何处理这些情况
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])
由于缺少值,当前正在获取超出上述范围的列表索引
您需要访问行,然后是列:
total_sum = 0
for i in [0, 1, 3, 5]:
total_sum += monthly_values[i][1]
这使您可以“手动”访问。 @Asger 的回答是自动的。
所以我上次使用 DjangoORM 已经有一段时间了,但是你可以做类似的事情
from datetime import date
monthly_values: list[tuple[date, float]] = Items.objects.filter(trade_date__gte=quarter_start_date,
trade_date__lte=quarter_end_date).values_list('trade_date', 'price').order_by('trade_date')
然后创建一个函数,将我们输入的起始价格添加到结果中,然后添加不是该月第一天的所有价格。
def get_prices(month_and_prices: list[tuple[date, float]]) -> float:
res = month_and_prices[0][1]
res += sum([x[1] for x in month_and_prices[1:] if x[0].day > 1])
return res
这应该可以解决您的问题