Opened 15 years ago

Closed 15 years ago

Last modified 11 years ago

#10425 closed (fixed)

Bad SQL generated for Book.objects.values('author').annotate(Count('author')).count()

Reported by: kmassey Owned by:
Component: Database layer (models, ORM) Version: dev
Severity: Keywords: values annotate count
Cc: Triage Stage: Accepted
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no


Observed with SVN revision 9984:


class Book(models.Model):
    title = models.CharField(max_length=200)
    author = models.CharField(max_length=200)

When using values() with annotate(), the count() method generates bad SQL:

$ python shell
Python 2.6.1 (r261:67515, Dec  6 2008, 16:42:21) 
[GCC 4.0.1 (Apple Computer, Inc. build 5370)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from example.models import *
>>> from django.db.models import Count
>>> qs = Book.objects.values('author').annotate(Count('author'))
>>> qs.count()
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/Users/kevin/django/bug/annotate_count/django/db/models/", line 329, in count
    return self.query.get_count()
  File "/Users/kevin/django/bug/annotate_count/django/db/models/sql/", line 345, in get_count
    number = obj.get_aggregation()[None]
  File "/Users/kevin/django/bug/annotate_count/django/db/models/sql/", line 317, in get_aggregation
    result = query.execute_sql(SINGLE)
  File "/Users/kevin/django/bug/annotate_count/django/db/models/sql/", line 2097, in execute_sql
    cursor.execute(sql, params)
  File "/Users/kevin/django/bug/annotate_count/django/db/backends/", line 19, in execute
    return self.cursor.execute(sql, params)
  File "/Users/kevin/django/bug/annotate_count/django/db/backends/sqlite3/", line 190, in execute
    return Database.Cursor.execute(self, query, params)
OperationalError: near "FROM": syntax error

The SQL that gets generated is malformed:

SELECT  FROM (SELECT "example_book"."author" AS author, COUNT("example_book"."author") FROM "example_book" GROUP BY "example_book"."author") subquery

Change History (5)

comment:1 Changed 15 years ago by Jacob

milestone: 1.1
Triage Stage: UnreviewedAccepted

comment:2 Changed 15 years ago by Alen Ribic

Has this been fixed? I can't simulate the problem my end. My qs.count() returns a correct value with no exception.


comment:3 Changed 15 years ago by Russell Keith-Magee

Resolution: fixed
Status: newclosed

(In [10053]) Fixed #10425 -- Corrected the interaction of .count() with .annotate() when .values() is also involved. Thanks to kmassey for the report.

comment:4 Changed 12 years ago by Jacob

milestone: 1.1

Milestone 1.1 deleted

comment:5 Changed 11 years ago by Anssi Kääriäinen

Component: ORM aggregationDatabase layer (models, ORM)
Note: See TracTickets for help on using tickets.
Back to Top