Changes between Version 1 and Version 2 of Ticket #24431
- Timestamp:
- Feb 28, 2015, 1:09:38 PM (10 years ago)
Legend:
- Unmodified
- Added
- Removed
- Modified
-
Ticket #24431
- Property Summary Combining extra(), annotate() or distinct() and count() can generate invalid SQL generation → Combining 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, theSQL will be invalid.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 tables. If the `extra()` components rely on those tables, the generated SQL will be invalid. 2 2 3 3 The 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). 4 4 5 5 Example: 6 {{{#!python 6 7 Permission.objects.all().select_related('content_type').extra(select={'foo':"django_content_type.app_label>'q'"}).distinct().count() 7 8 }}} 9 {{{ 8 10 ProgrammingError: missing FROM-clause entry for table "django_content_type" 9 11 LINE 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 }}} 13 Remove the `distinct()`, or the `count()`, and it's fine (this is a contrived example, I know it makes no practical sense). 12 14 13 15 Another Example with some toy models: … … 26 28 Author.objects.all().annotate(blogpost_count=Count('blogpost')).select_related('address').extra(select={'in_maryland':"address.state='MD'"}).count() 27 29 }}} 28 This is fine until you append the count()30 This is fine until you append the `count()` 29 31 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.32 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. 31 33 32 A potential fix is in django/db/models/sql/query.py line 396 in get_aggregation().34 A potential fix is in `django/db/models/sql/query.py` line `396` in `get_aggregation()`. 33 35 Change 34 36 {{{#!python