Django union by day name

I tried to do "aggregation of the day of the week", I have this code:

IN:

MyMode.objects.values('day').annotate(Sum('visits'))

OUT:

[{'visits__sum': 44, 'day': datetime.datetime(2015, 4, 5, 0, 0)},
{'visits__sum': 699, 'day': datetime.datetime(2015, 9, 6, 0, 0)},     
{'visits__sum': 3, 'day': datetime.datetime(2015, 9, 3, 0, 0)}, 
{'visits__sum': 12, 'day': datetime.datetime(2011, 4, 5, 0, 0)}]

But I want to aggregate by day name, not by number. I need full visits on Monday, Tuesday, etc. Monday from 2015.08 should be in the same "bag" where on Monday from 2015.06 or 2012.02.

+4
source share
2 answers

For Django 1.8+:

from django.db.models import Func

class DayOfWeek(Func):
    """ Sunday == 0, ..., Saturday == 6 """
    template = 'extract(dow from %(expressions)s)'

>>> (
    MyMode.objects.annotate(dow=DayOfWeek(F('day')))
                  .values('dow')
                  .annotate(c=Count('dow'))
)

[{'c': 185, 'dow': 0.0}, {'c': 178, 'dow': 5.0}]

For Django 1.7-, I believe that you need to execute a raw request.

+1
source

I don't think this is the solution you expect, but maybe it can help you:

on Sundays:

MyMode.objects.values('day').annotate(Sum('visits')).filter(day__week_day=1)

Change the filter value for other holidays. Days start with Sunday=1, Monday=2,etc.

0
source

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


All Articles