Wednesday, June 29, 2016

Is this behavior with Meta Ordering and Group By expected?

Hello!

I'm using Django 1.9.7, MySQL innodb 5.7.11, and python 2.7.10.

I noticed some strange behavior when running this query:
q = A.objects.values('b').annotate(most_recent=Max('created_at'))

Produces this SQL:
SELECT `core_a`.`b_id`, MAX(`core_a`.`created_at`) AS `most_recent` FROM `core_a` GROUP BY `core_a`.`id` ORDER BY `core_a`.`id` ASC

which groups by an unexpected field.  I was expecting it to group by `core_a`.`b_id` rather than `core_a`.`id`.

Here are my models:
from __future__ import unicode_literals

from django.db import models
from django.utils import timezone


class B(models.Model):
    created_at = models.DateTimeField(default=timezone.now)


class A(models.Model):
    created_at = models.DateTimeField(default=timezone.now)
    b = models.ForeignKey(B)

    class Meta:
        ordering = ["id"]


If I remove from model A these lines 
    class Meta:
        ordering = ["id"]
then the query produces SQL which groups by the b_id column as expected.

Is this known behavior?  Would this be considered a bug?

Thanks,
-Eric

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/d06683cc-ea7b-43db-a23b-0ebbd19bd424%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment