Opened 16 years ago

Closed 16 years ago

Last modified 16 years ago

#9799 closed (wontfix)

django.db.models.sql.query.BaseQuery.get_count() works wrong with GROUP BY

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

Description

Query produced by get_count is

SELECT COUNT(*) FROM table

which returned one row, f.e. (5) . Ok, it's works.
Lets add an GROUP BY statement:

SELECT COUNT(*) FROM table GROUP BY field

It's returned an list of row with count of grouped rows, f.e. (4, 23, 1, 1, 5)
In ge_count we see

data = obj.execute_sql(SINGLE)
if not data:
    return 0
number = data[0]

So it's return only first value of the list instead of list's width. With our example it's 5.
Solutions are:

  1. Return cursor's row_count
  2. Modify query to
    SELECT (*) FROM (SELECT COUNT(*) FROM table GROUP BY field) AS t
    

Change History (2)

comment:1 by Malcolm Tredinnick, 16 years ago

Resolution: wontfix
Status: newclosed

This is true, but it's not currently intended to work with group_by. This is noted in the comment where the count query is set up. Making this work is part of the broader "adding aggregation" support to Django scheduled for 1.1. You'll want to follow #3566 for progress on that if you're interested.

Closing as wontfix, since the limitation is intentional, and the API you're using is not public API (there's no public group_by API at the moment) and we're developing the public API in #3566.

comment:2 by bcurtu, 16 years ago

I know this bug/feature is fixed/implemented in django 1.1, however, since I can not move from 1.0 I have patched this problem:

Index: /home/bcm/wsp/www/django/db/models/sql/query.py
===================================================================
--- /home/bcm/wsp/www/django/db/models/sql/query.py	(revision 2833)
+++ /home/bcm/wsp/www/django/db/models/sql/query.py	(working copy)
@@ -228,6 +228,7 @@
         obj.select_related = False
         obj.related_select_cols = []
         obj.related_select_fields = []
+        obj.group_by=[] 
         if len(obj.select) > 1:
             obj = self.clone(CountQuery, _query=obj, where=self.where_class(),
                     distinct=False)

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