Issue
I've already read this Django: Group by date (day, month, year) and all related stuff by googling "django group by month"
If I try the "cleanest" solution - using Django 1.11, I end up with this:
class Request(BaseModel):
date_creation = models.DateTimeField(default=None,
blank=True, null=True)
print([v for v in
Request.objects.annotate(month=ExtractMonth('date_creation'),
year=ExtractYear('date_creation'),)
.values('month', 'year')
.annotate(total=Count('month'))
.values('month', 'year', 'total')
])
And the result doesn't do a group by! I get this:
[{'month': 6, 'year': 2017, 'total': 1},
{'month': 7, 'year': 2017, 'total': 1},
{'month': 7, 'year': 2017, 'total': 1}]
I need to get:
[{'month': 6, 'year': 2017, 'total': 1},
{'month': 7, 'year': 2017, 'total': 2}]
I've also tried:
print([v for v in
Request.objects.extra({'month': 'strftime("%m", date_creation)',
'year': 'strftime("%Y", date_creation)'})
.values('month', 'year')
.annotate(total=Count('*'))
.values('month', 'year', 'total')
])
And then I get:
[{'month': '06', 'year': '2017', 'total': 1},
{'month': '07', 'year': '2017', 'total': 1},
{'month': '07', 'year': '2017', 'total': 1}]
Any idead?
Solution
I found the problem thanks to PyCharm. I seriously dont know how I could have found the solution without that IDE. The more I'm using it the more I find it powerful. Then I found the solution thanks to this: How can I remove Model Meta ordering in Django or get the original queryset from the built in Manager?
My Request
model has a parent which has a field date_creation
and a class Meta:
with ordering = ['date_creation']
.
So if you don't add order_by('field_xx')
in your query, then Django automagically add this: order_by('date_creation')
.
Thus my query looked like:
SELECT
(strftime("%m", date_creation)) AS "month",
(strftime("%Y", date_creation)) AS "year",
COUNT(*) AS "total" FROM "app_request"
GROUP BY
(strftime("%m", date_creation)),
(strftime("%Y", date_creation)),
"app_request"."date_creation"
And it broke the query.
The solution was:
from django.db.models.functions.datetime import ExtractMonth, ExtractYear
print([v for v in
Request.objects.annotate(month=ExtractMonth('date_creation'),
year=ExtractYear('date_creation'),)
.order_by()
.values('month', 'year')
.annotate(total=Count('*'))
.values('month', 'year', 'total')
])
Actually, my solution was working from the very beginning!
Answered By - Olivier Pons
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.