Skip to content

Instantly share code, notes, and snippets.

@browniebroke
Last active August 29, 2015 14:19
Show Gist options
  • Save browniebroke/a62fb59ffee37aa8bf04 to your computer and use it in GitHub Desktop.
Save browniebroke/a62fb59ffee37aa8bf04 to your computer and use it in GitHub Desktop.
Django: Group model & count by date
"""
Generic method (disclaimer: I did not consider any security concerns) to get stats
on a model in Django.
Created from http://stackoverflow.com/questions/8746014/django-group-sales-by-month
"""
from django.db import connection
from django.db.models import Sum, Count
def truncate_date_model(model, period_length, date_field, criteria=None, pk='pk'):
"""
model is the model class (Model, not instance nor model name as string)
period_length is a string 'month', 'week', 'year' or 'quarter' for instance
date_field is the string of the model's field to be truncated upon 'datetime', 'created'
criteria is another optional field name, which may differentiate several series
"""
truncate_date = connection.ops.date_trunc_sql(period_length, date_field)
qs = model.objects.extra({period_length: truncate_date})
if criteria:
return qs.values(period_length, criteria).annotate(Count(criteria)).order_by(period_length)
return qs.values(period_length).annotate(Count(pk)).order_by(period_length)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment