Code

Opened 9 months ago

Closed 9 months ago

#20782 closed Bug (fixed)

Aggregating annotations raises DatabaseError

Reported by: debanshuk Owned by: nobody
Component: Database layer (models, ORM) Version: 1.5
Severity: Normal Keywords:
Cc: debanshuk 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.

Attachments (0)

Change History (2)

comment:1 Changed 9 months ago by debanshuk

  • Cc debanshuk added
  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset

comment:2 Changed 9 months ago by Anssi Kääriäinen <akaariai@…>

  • Resolution set to fixed
  • Status changed from new to closed

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.

Add Comment

Modify Ticket

Change Properties
<Author field>
Action
as closed
as The resolution will be set. Next status will be 'closed'
The resolution will be deleted. Next status will be 'new'
Author


E-mail address and user name can be saved in the Preferences.

 
Note: See TracTickets for help on using tickets.