Opened 7 years ago

Closed 7 years ago

Last modified 7 years ago

#28705 closed Bug (needsinfo)

Wrong annotation when used with QuerySet.order_by()

Reported by: Rafael Capucho Owned by: nobody
Component: Database layer (models, ORM) Version: 1.11
Severity: Normal Keywords: Annotate, ORM, Order_by
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Related to old closed ticket: https://code.djangoproject.com/ticket/25316

# Models

class Application(models.Model):
    package_name = models.CharField(max_length=128, null=False, blank=True)
    package_version_code = models.IntegerField(blank=True)
    package_version_name = models.CharField(max_length=64, null=False, blank=True)
    label = models.CharField(max_length=64, null=False, blank=True)

    class Meta:
        ordering = ['label', 'package_version_code']

class Profile(models.Model):
    applications = models.ManyToManyField(
        'applications.Application',
        related_name='application_%(class)s',
        blank=True
    )

class Device(models.Model):
   profile = models.ForeignKey(
        Profile,
        related_name='devices',
        blank=True,
        null=True
    )

The error is:
https://i.imgur.com/JbUyRQJ.png

Attachments (1)

JbUyRQJ.png (82.4 KB ) - added by Rafael Capucho 7 years ago.

Download all attachments as: .zip

Change History (4)

by Rafael Capucho, 7 years ago

Attachment: JbUyRQJ.png added

comment:1 by Tim Graham, 7 years ago

Component: UncategorizedDatabase layer (models, ORM)
Summary: Wrong annotation when used with order_byWrong annotation when used with QuerySet.order_by()

Could you add a tests.py file that demonstrates the issue (and/or replace the screenshot in the description)? The screenshot isn't particularly friendly for someone trying to reproduce this since they have to retype everything.

Did you read the aggregation topic guide to ensure that none of the documented issues there are the cause of the behavior?

comment:2 by Tomer Chachamu, 7 years ago

It looks like this section explains the behaviour: https://docs.djangoproject.com/en/1.11/topics/db/aggregation/#interaction-with-default-ordering-or-order-by

Maybe you want to use .annotate(...).order_by('label', 'latest') instead?

comment:3 by Tomer Chachamu, 7 years ago

Resolution: needsinfo
Status: newclosed

Also, if you can provide the output that you expected for each of the queries, that would help us understand the issue :)

Version 0, edited 7 years ago by Tomer Chachamu (next)
Note: See TracTickets for help on using tickets.
Back to Top