Django Monthly/quartarly grouping of DateField() data

ぐ巨炮叔叔 提交于 2019-12-21 20:48:29

问题


I've got a django model which contains, among other things, a DateField() attribute:

class Table():
    date = models.DateField()
    value = models.FloatField()

I'm writing a view that groups this data by week, month Quarter and year. I've hardcoded a calculation that gets my monthly value simply enough - by adding up all the values in that month and deviding by how many entries there were - but I feel like there must be a more elegant way of doing this.

What I'm aiming for is something like this:

get_monthly(Table.objects.all())
>>> [123, 412, 123, 534, 234, 423, 312, 412, 123, 534, 234, 423]
get_quarterly(Table.objects.all())
>>> [123, 412, 123, 534]

Where the values in the list are averages of each month.

Can anyone help me?


回答1:


You can do this using the model's query capabilities. Here's an example for the monthly query:

from django.db.models import Avg
Table.objects.extra(select={'month':"strftime('%m',date)"}).values('month').annotate(Avg('value'))

Where you may want to change strftime('%m',date) with month(date) or any other calculation, depending on your database datetime functionality.



来源:https://stackoverflow.com/questions/3907240/django-monthly-quartarly-grouping-of-datefield-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!