Reputation: 229
I've tried make 'day of week aggregation', 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 the name of day, not the number. I need totally visits in Monday, Tuesday, etc. Monday from 2015.08 should be in the same 'bag' where Monday from 2015.06 or 2012.02.
Upvotes: 4
Views: 201
Reputation: 15854
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 you need to do a raw query.
Upvotes: 1
Reputation: 10256
I don't think this is the solution you are expecting for, but maybe can help you:
for Sundays:
MyMode.objects.values('day').annotate(Sum('visits')).filter(day__week_day=1)
Change the filter value for the other weekend days. Days starts in Sunday=1, Monday=2,
etc.
Upvotes: 0