Opened 7 years ago
Closed 7 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 , 7 years ago
| Cc: | added |
|---|
comment:2 by , 7 years ago
| Component: | Uncategorized → Database layer (models, ORM) |
|---|---|
| Triage Stage: | Unreviewed → Accepted |
comment:4 by , 7 years ago
| Patch needs improvement: | set |
|---|
Removing the deprecation from #14357 isn't appropriate.
comment:5 by , 7 years ago
| Patch needs improvement: | unset |
|---|
comment:6 by , 7 years ago
| Resolution: | → wontfix |
|---|---|
| Status: | new → closed |
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.
I'm not sure how this should be solved. The problem is that adding that
order_by()clause to a model withoutMeta.orderingdoesn'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)