Last active
November 22, 2021 13:20
-
-
Save alvingonzales/ff9333e39d221981e5fc4cd6cdafdd17 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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