(Is it a bug?) TruncMonth does not work when there is "ordering" in the model Meta (Django 1.10)

159 views
Skip to first unread message

Neto

unread,
Aug 10, 2016, 7:44:33 PM8/10/16
to Django users
I'm trying to get number of records per month, but Django does not return correctly when there is "ordering" in class Meta Model.

I have the Abc model, with 4 records made this month, look what happens (Django 1.10, PostgreSQL):

class Abc(Base):

class Meta:
ordering = ['-date_pub']

>>> Abc.objects.annotate(month=TruncMonth('created_at')).values('month').annotate(total=Count('id')).values('total')
<QuerySet [{'total': 1}, {'total': 1}, {'total': 1}, {'total': 1}]>

Without "ordering"

class Abc(Base):
pass

>>> Abc.objects.annotate(month=TruncMonth('created_at')).values('month').annotate(total=Count('id')).values('total')
<QuerySet [{'total': 4}]>

Why this happens? Is it a bug?

Tim Graham

unread,
Aug 10, 2016, 8:17:31 PM8/10/16
to Django users

Neto

unread,
Aug 10, 2016, 8:41:29 PM8/10/16
to Django users
Thanks! Should have a note about it on the page "database-funcions":
https://docs.djangoproject.com/en/1.10/ref/models/database-functions/#trunc

Tim Graham

unread,
Aug 11, 2016, 12:02:01 AM8/11/16
to Django users
Unfortunately, I don't think mentioning the issue every place where someone might be doing an aggregation query is practical. I did recently add a link about it to the Meta.ordering docs recently [0], so hopefully that helps raise awareness.

[0] https://github.com/django/django/commit/3aaf6cf0f3288986c4ce56defea26420f8a48534
Reply all
Reply to author
Forward
0 new messages