Opened 11 years ago

Closed 11 years ago

#20782 closed Bug (fixed)

Aggregating annotations raises DatabaseError

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

Description

If I have a model Book defined as:

class Book(models.Model):
   name = models.CharField(max_length=300)
   pages = models.IntegerField()
   price = models.DecimalField(max_digits=10, decimal_places=2)
   rating = models.FloatField()
   pubdate = models.DateField()

and I run the query:

Book.objects.values('rating').annotate(books_per_rating=Count('id')).aggregate(Max('books_per_rating'))

I get a DatabaseError.

According to this https://docs.djangoproject.com/en/1.5/topics/db/aggregation/#aggregating-annotations, Django supports aggregating annotations. But in the example given in the link itself, they annotate over a QuerySet which in turn returns a QuerySet (and not ValuesQuerySet), so aggregate method runs successfully. But in my example aggregating a ValuesQuerySet raises a DatabaseError.

Is it a bug in Django? Because if Django does not support aggregation over ValuesQuerySet then it should raise an exception at Django level (not DatabaseError).

Also interestingly, if I do:

Book.objects.values('rating').aggregate(Max('rating'))

It returns an empty dict without performing any DB query!!

Note: Error was raised on 'postgresql_psycopg2' and 'sqlite3' backends. Haven't been tested on other backends.

Change History (2)

comment:1 by Debanshu Kundu, 11 years ago

Cc: Debanshu Kundu added

comment:2 by Anssi Kääriäinen <akaariai@…>, 11 years ago

Resolution: fixed
Status: newclosed

In 4bd55547214ae149acadffe60536c379d51e318f:

Fixed #20782 -- qs.values().aggregate() failure

In the combination of .values().aggregate() the aggregate_select_mask
didn't include the aggregates added. This resulted in bogus query.

Thanks to Trac alias debanshuk for report.

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