django 聚合多天

标签 django database performance aggregate

我有一个具有两个属性的模型:日期和长度以及其他不相关的属性。我需要在模板中显示每天的长度总和列表。

到目前为止我使用的解决方案是每天循环并使用如下聚合创建总和列表:

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.

希望这对您有所帮助。

关于django 聚合多天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31899047/

相关文章:

python - 从 dev : static files not resolving 中的子文件夹提供 django

python - 多对多关系的 Django 方向

java - 如何从 Java 备份 mysql 数据库?

java - 在 Java 中使用 BigDecimal 打印值

python - NumPy 数学函数比 Python 更快吗?

mysql - Django 1.5 查询包含来自其他模型的列

Django 1.7 中的 Django-migrations 检测模型更改,但不会将其应用于迁移

java - Android SHA1 非常慢

database - 将 postgres 服务器扩展到多个服务器

magento - Magento加载时间的瓶颈在哪里