|
10 | 10 | NullBooleanField, OuterRef, Q, Subquery, Sum, Value, When, |
11 | 11 | ) |
12 | 12 | from django.db.models.expressions import RawSQL |
13 | | -from django.db.models.functions import Length, Lower |
| 13 | +from django.db.models.functions import ExtractYear, Length, Lower |
14 | 14 | from django.test import TestCase, skipUnlessDBFeature |
15 | 15 |
|
16 | 16 | from .models import ( |
@@ -664,6 +664,25 @@ def test_annotation_exists_aggregate_values_chaining(self): |
664 | 664 | datetime.date(2008, 11, 3), |
665 | 665 | ]) |
666 | 666 |
|
| 667 | + @skipUnlessDBFeature('supports_subqueries_in_group_by') |
| 668 | + def test_annotation_subquery_and_aggregate_values_chaining(self): |
| 669 | + qs = Book.objects.annotate( |
| 670 | + pub_year=ExtractYear('pubdate') |
| 671 | + ).values('pub_year').annotate( |
| 672 | + top_rating=Subquery( |
| 673 | + Book.objects.filter( |
| 674 | + pubdate__year=OuterRef('pub_year') |
| 675 | + ).order_by('-rating').values('rating')[:1] |
| 676 | + ), |
| 677 | + total_pages=Sum('pages'), |
| 678 | + ).values('pub_year', 'total_pages', 'top_rating') |
| 679 | + self.assertCountEqual(qs, [ |
| 680 | + {'pub_year': 1991, 'top_rating': 5.0, 'total_pages': 946}, |
| 681 | + {'pub_year': 1995, 'top_rating': 4.0, 'total_pages': 1132}, |
| 682 | + {'pub_year': 2007, 'top_rating': 4.5, 'total_pages': 447}, |
| 683 | + {'pub_year': 2008, 'top_rating': 4.0, 'total_pages': 1178}, |
| 684 | + ]) |
| 685 | + |
667 | 686 | @skipIf( |
668 | 687 | connection.vendor == 'mysql' and 'ONLY_FULL_GROUP_BY' in connection.sql_mode, |
669 | 688 | 'GROUP BY optimization does not work properly when ONLY_FULL_GROUP_BY ' |
|
0 commit comments