Changes between Version 1 and Version 2 of Ticket #24431


Ignore:
Timestamp:
Feb 28, 2015, 1:09:38 PM (9 years ago)
Author:
briankrznarich
Comment:

Legend:

Unmodified
Added
Removed
Modified
  • Ticket #24431

    • Property Summary Combining extra(), annotate() or distinct() and count() can generate invalid SQL generationCombining extra(), annotate() or distinct() and count() can generate invalid SQL
  • Ticket #24431 – Description

    v1 v2  
    1 When applying a count() to a queryset that contains extra() values and either an annotation, or a distinct() call, get_aggregation() discards any existing select_related entries.  If the extra() components rely on those joins, the SQL will be invalid.
     1When applying a `count()` to a queryset that contains `extra()` values and either an `annotation` or a `distinct()` call, `get_aggregation()` discards any existing select_related tables.  If the `extra()` components rely on those tables, the generated SQL will be invalid.
    22
    33The failures are new to 1.8, and do not appear to be present in 1.7. (I discovered the problem when upgrading fom 1.7 to beta for testing).
    44
    55Example:
     6{{{#!python
    67Permission.objects.all().select_related('content_type').extra(select={'foo':"django_content_type.app_label>'q'"}).distinct().count()
    7 
     8}}}
     9{{{
    810ProgrammingError: missing FROM-clause entry for table "django_content_type"
    911LINE 1: SELECT COUNT('*') FROM (SELECT DISTINCT (django_content_type.
    10 
    11 Remove the distinct(), or the count(), and it's fine (this is a contrived example, I know it makes no practical sense).
     12}}}
     13Remove the `distinct()`, or the `count()`, and it's fine (this is a contrived example, I know it makes no practical sense).
    1214
    1315Another Example with some toy models:
     
    2628Author.objects.all().annotate(blogpost_count=Count('blogpost')).select_related('address').extra(select={'in_maryland':"address.state='MD'"}).count()
    2729}}}
    28 This is fine until you append the count()
     30This is fine until you append the `count()`
    2931
    30 We hit this issue where TastyPie applies count() to then end of some complicated querysets, far far away from where we constructed them.   In our case, we're using extra() values for an order_by that requires several comparisons.   
     32We hit this issue where TastyPie applies `count()` to then end of some complicated querysets, far far away from where we constructed them.   In our case, we're using `extra()` values for an order_by that requires several comparisons.   
    3133
    32 A potential fix is in django/db/models/sql/query.py line 396 in get_aggregation().
     34A potential fix is in `django/db/models/sql/query.py` line `396` in `get_aggregation()`.
    3335Change
    3436{{{#!python
Back to Top