Django Monthly / Quarterly Data Grouping DateField ()

I have a django model that contains, among other things, the DateField () attribute :

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

I am writing a presentation that groups this data by week, month, quarter and year. I hard-coded a calculation that gets my monthly value quite simply - by summing up all the values ​​this month and determining the number of records, but I feel that there should be a more elegant way to do 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]

If the values ​​in the list are average for each month.

Can anybody help me?

+2
source share
1 answer

, . :

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

strftime('%m',date) month(date) , datetime.

+2

Source: https://habr.com/ru/post/1621983/


All Articles