django 聚合多天
django aggregate for multiple days
我有一个模型,它有两个属性:日期和长度以及其他不相关的属性。我需要在模板中显示每一天的长度总和列表。
到目前为止我使用的解决方案是每天循环并使用如下聚合创建总和列表:
for day in month:
sums.append(MyModel.objects.filter(date=date).aggregate(Sum('length')))
但由于数据库查找的数量,对我来说它似乎非常无效。有没有更好的方法来做到这一点?喜欢缓存所有内容然后在不触及数据库的情况下对其进行过滤?
.values()
可用于按 date
分组,因此您只会得到 唯一的 日期以及 length
字段的总和通过 .annotate()
:
>>> from django.db.models import Sum
>>> MyModel.objects.values('date').annotate(total_length=Sum('length'))
来自docs:
When .values() clause is used to constrain the columns that are returned in the result set, the method for evaluating annotations is slightly different. Instead of returning an annotated result for each result in the original QuerySet, the original results are grouped according to the unique combinations of the fields specified in the .values() clause.
希望对您有所帮助。
我有一个模型,它有两个属性:日期和长度以及其他不相关的属性。我需要在模板中显示每一天的长度总和列表。
到目前为止我使用的解决方案是每天循环并使用如下聚合创建总和列表:
for day in month:
sums.append(MyModel.objects.filter(date=date).aggregate(Sum('length')))
但由于数据库查找的数量,对我来说它似乎非常无效。有没有更好的方法来做到这一点?喜欢缓存所有内容然后在不触及数据库的情况下对其进行过滤?
.values()
可用于按 date
分组,因此您只会得到 唯一的 日期以及 length
字段的总和通过 .annotate()
:
>>> from django.db.models import Sum
>>> MyModel.objects.values('date').annotate(total_length=Sum('length'))
来自docs:
When .values() clause is used to constrain the columns that are returned in the result set, the method for evaluating annotations is slightly different. Instead of returning an annotated result for each result in the original QuerySet, the original results are grouped according to the unique combinations of the fields specified in the .values() clause.
希望对您有所帮助。