Skip to content

Instantly share code, notes, and snippets.

@alvingonzales
Last active November 22, 2021 13:20
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save alvingonzales/ff9333e39d221981e5fc4cd6cdafdd17 to your computer and use it in GitHub Desktop.
Save alvingonzales/ff9333e39d221981e5fc4cd6cdafdd17 to your computer and use it in GitHub Desktop.
# sample implementation for http://stackoverflow.com/questions/37851053/django-query-group-by-month#new-answer
from __future__ import unicode_literals
from django.db import models
from django.db.models import Func, F, Sum
from django.db.transaction import atomic, rollback
from django.utils.timezone import now
class Invoice(models.Model):
datetime = models.DateTimeField()
total = models.IntegerField(default=100)
class Month(Func):
function = 'EXTRACT'
template = '%(function)s(MONTH from %(expressions)s)'
output_field = models.IntegerField()
class MonthSqlite(Func):
function = 'STRFTIME'
template = '%(function)s("%%m", %(expressions)s)'
output_field = models.CharField()
def test():
TESTDATA = [
(7, 300),
(7, 200),
(3, 100),
(4, 500),
(1, 100),
]
with atomic():
for m, total in TESTDATA:
Invoice(datetime=now().replace(day=1, month=m), total=total).save()
summary = (Invoice.objects
.annotate(m=MonthSqlite('datetime'))
.values('m')
.annotate(total=Sum('total'))
.order_by())
for result in summary:
print result
raise Exception('stop')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment