| 1 | from django.test import TestCase |
| 2 | from django.db.models import Max |
| 3 | |
| 4 | from regressiontests.aggregation_regress.models import * |
| 5 | |
| 6 | |
| 7 | class AggregationTests(TestCase): |
| 8 | |
| 9 | def test_aggregates_in_where_clause(self): |
| 10 | """ |
| 11 | Regression test for #12822: DatabaseError: aggregates not allowed in |
| 12 | WHERE clause |
| 13 | |
| 14 | Tests that the subselect works and returns results equivalent to a |
| 15 | query with the IDs listed. |
| 16 | |
| 17 | Before the corresponding fix for this bug, this test passed in 1.1 and |
| 18 | failed in 1.2-beta (trunk). |
| 19 | """ |
| 20 | qs = Book.objects.values('contact').annotate(Max('id')) |
| 21 | qs = qs.order_by('contact').values_list('id__max', flat=True) |
| 22 | # don't do anything with the queryset (qs) before including it as a |
| 23 | # subquery |
| 24 | books = Book.objects.order_by('id') |
| 25 | qs1 = books.filter(id__in=qs) |
| 26 | qs2 = books.filter(id__in=list(qs)) |
| 27 | self.assertEqual(list(qs1), list(qs2)) |
| 28 | |
| 29 | def test_aggregates_in_where_clause_pre_eval(self): |
| 30 | """ |
| 31 | Regression test for #12822: DatabaseError: aggregates not allowed in |
| 32 | WHERE clause |
| 33 | |
| 34 | Same as the above test, but evaluates the queryset for the subquery |
| 35 | before it's used as a subquery. |
| 36 | |
| 37 | Before the corresponding fix for this bug, this test failed in both |
| 38 | 1.1 and 1.2-beta (trunk). |
| 39 | """ |
| 40 | qs = Book.objects.values('contact').annotate(Max('id')) |
| 41 | qs = qs.order_by('contact').values_list('id__max', flat=True) |
| 42 | # force the queryset (qs) for the subquery to be evaluated in its |
| 43 | # current state |
| 44 | list(qs) |
| 45 | books = Book.objects.order_by('id') |
| 46 | qs1 = books.filter(id__in=qs) |
| 47 | qs2 = books.filter(id__in=list(qs)) |
| 48 | self.assertEqual(list(qs1), list(qs2)) |