Django annotate groupings by month
I have a very basic model:
class Link(models.Model):
title = models.CharField(max_length=250, null=False)
user = models.ForeignKey(User)
url = models.CharField(max_length=250, blank=True, null=True)
link_count = models.IntegerField(default=0)
pub_date = models.DateField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
I can create a list of al开发者_运维技巧l the entries grouped by date using:
Link.objects.values('pub_date').order_by('-pub_date').annotate(dcount=Count('pub_date'))
This will naturally group items by day. But what I really want to do is group by month. Is there anyway I can do this using annotate()?
Many thanks,
G
If you're on PostgreSQL, the following might work:
from django.db.models import Count
Link.objects.extra(select={'month': 'extract( month from pub_date )'}).values('month').annotate(dcount=Count('pub_date'))
I'm not sure how portable extract
is across other databases.
from django.db import connections
from django.db.models import Count
Link.objects.extra(select={'month': connections[Link.objects.db].ops.date_trunc_sql('month', 'pub_date')}).values('month').annotate(dcount=Count('pub_date'))
To add, as an alternative for using extra()
: since Django 1.8, you can also use conditional expressions.
>>> year_overview = Link.objects.filter(pub_date__year=year).aggregate(
jan=Sum(
Case(When(created__month=0, then=1),
output_field=IntegerField())
),
feb=Sum(
Case(When(created__month=1, then=1),
output_field=IntegerField())
),
mar=Sum(
Case(When(created__month=2, then=1),
output_field=IntegerField())
),
apr=Sum(
Case(When(created__month=3, then=1),
output_field=IntegerField())
),
may=Sum(
Case(When(created__month=4, then=1),
output_field=IntegerField())
),
jun=Sum(
Case(When(created__month=5, then=1),
output_field=IntegerField())
),
jul=Sum(
Case(When(created__month=6, then=1),
output_field=IntegerField())
),
aug=Sum(
Case(When(created__month=7, then=1),
output_field=IntegerField())
),
sep=Sum(
Case(When(created__month=8, then=1),
output_field=IntegerField())
),
oct=Sum(
Case(When(created__month=9, then=1),
output_field=IntegerField())
),
nov=Sum(
Case(When(created__month=10, then=1),
output_field=IntegerField())
),
dec=Sum(
Case(When(created__month=11, then=1),
output_field=IntegerField())
),
)
>>> year_overview
{'mar': None, 'feb': None, 'aug': None, 'sep': 95, 'apr': 1, 'jun': None, 'jul': None, 'jan': None, 'may': None, 'nov': 87, 'dec': 94, 'oct': 100}
I've read that .extra()
will be deprecated in the future. They are suggesting to instead use Func
objects. And there is one for extracting a month without using a painful Case
statement.
from django.db.models.functions import ExtractMonth
Link.objects.all().annotate(pub_date_month=ExtractMonth('pub_date'))
精彩评论