Opened 6 years ago

Closed 6 years ago

#29539 closed Bug (wontfix)

Cannot use Aggregation function in Model.Meta.ordering

Reported by: wilhelmhb Owned by: nobody
Component: Database layer (models, ORM) Version: 2.0
Severity: Normal Keywords: ordering, query expression, aggregation function
Cc: wilhelmhb, Can Sarıgöl Triage Stage: Accepted
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Modifying the example from https://docs.djangoproject.com/en/2.0/topics/db/queries/# to add ordering:

from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=200)

class Entry(models.Model):
    headline = models.CharField(max_length=255)
    authors = models.ManyToManyField(Author)

    def __str__(self):
        return self.headline

    class Meta:
        ordering = [
            models.Min('authors__id').asc(),
            models.Max('authors__id').asc()
        ]

The query to get entries will fail with a ProgrammingError: the SQL query doesn't contain the GROUP BY clause.
As aggregation functions are QueryExpression objects, and the ordering field handles QueryExpressions since Django 2.0, it should work.

Change History (6)

comment:1 by wilhelmhb, 6 years ago

Cc: wilhelmhb added

comment:2 by Tim Graham, 6 years ago

Component: UncategorizedDatabase layer (models, ORM)
Triage Stage: UnreviewedAccepted

I'm not sure how this should be solved. The problem is that adding that order_by() clause to a model without Meta.ordering doesn't work:

>>> Entry.objects.order_by(models.Min('authors__id').asc(), models.Max('authors__id').asc()))
...
django.core.exceptions.FieldError: Using an aggregate in order_by() without also including it in annotate() is not allowed: OrderBy(Min(F(authors__id)), descending=False)

comment:3 by Can Sarıgöl, 6 years ago

Cc: Can Sarıgöl added
Has patch: set

I tried to fix this. Could you review? PR

comment:4 by Tim Graham, 6 years ago

Patch needs improvement: set

Removing the deprecation from #14357 isn't appropriate.

comment:5 by Can Sarıgöl, 6 years ago

Patch needs improvement: unset

comment:6 by Tim Graham, 6 years ago

Resolution: wontfix
Status: newclosed

From Simon on the pull request:

I think this feature would be hard to get right for the rare case where it's useful. It also go against our stance on trying to disconnect Meta.ordering from aggregation (#14357) as this PR demonstrates. I'd be in favour of won't fixing the ticket as well for these reasons. It feels incoherent with the ongoing deprecation motivated by observed user confusion over the years from the interactions between these two features.

Note: See TracTickets for help on using tickets.
Back to Top