3

I just upgraded from Django 1.6 to 1.8 due to numerous reasons. I noticed some changes in the displayed data on my application. Maybe someone can help me find the issue, please.

This is my code:

users = __apply_filters(User.objects.all(), request)
users = users.extra({
    'month': 'month(created)',
    'year': 'year(created)'
}).values('year', 'month').annotate(dcount=Count('created', distinct=True))

In the __apply_filters function I filter the data according to some filters.

When running the 1.6 project, I get this result:

[{'month': 11L, 'dcount': 4, 'year': 2015L}]

When running the 1.8 project, I get this result (with the same input data):

[{'month': 11L, 'dcount': 1, 'year': 2015L}, {'month': 11L, 'dcount': 1, 'year': 2015L}, {'month': 11L, 'dcount': 1, 'year': 2015L}, {'month': 11L, 'dcount': 1, 'year': 2015L}]

Obviously, this is displaying wrong data.

I would mention that my DataBase is MySQL. I need this kind of aggregation because I have date filtering and various charts displaying a timeline.

Has anyone encountered such a problem?

Thank you!

Alasdair
  • 298,606
  • 55
  • 578
  • 516
Irene Texas
  • 1,731
  • 2
  • 12
  • 8
  • Using `extra()` is discouraged where possible. You could try annotating the month and year with [func expressions](https://docs.djangoproject.com/en/1.8/ref/models/expressions/#func-expressions), to see whether that works. – Alasdair Nov 24 '15 at 09:46
  • Is `distinct` a valid argument for `count()`? I've never seen it before. – Alasdair Nov 24 '15 at 09:47
  • @Alasdair I needed the year and month from the created date and that's why I used `extra()` and `distinct` works in `count()`, it counts the distinct values. – Irene Texas Nov 24 '15 at 10:01
  • 1
    While I was still searching I also found the solution https://docs.djangoproject.com/en/1.8/topics/db/aggregation/#interaction-with-default-ordering-or-order-by The group by also takes into consideration any field I have in `ordering` in `class Meta`. The solution is a `order_by()` at the end. – Irene Texas Nov 24 '15 at 10:04
  • I know you need the year and month, but I don't think you need to use `extra()`. You should be able to use a func expression instead. Anyway, glad you found the problem. – Alasdair Nov 24 '15 at 10:11

0 Answers0