|
| 1 | +import datetime |
| 2 | +from decimal import Decimal |
| 3 | + |
| 4 | +from django.db.models import Count, Max, Q |
| 5 | +from django.test import TestCase |
| 6 | + |
| 7 | +from .models import Author, Book |
| 8 | + |
| 9 | + |
| 10 | +class FilteredAggregateTests(TestCase): |
| 11 | + @classmethod |
| 12 | + def setUpTestData(cls): |
| 13 | + cls.a1 = Author.objects.create(name="test", age=40) |
| 14 | + cls.a2 = Author.objects.create(name="test2", age=60) |
| 15 | + cls.a3 = Author.objects.create(name="test3", age=40) |
| 16 | + cls.b1 = Book.objects.create( |
| 17 | + isbn="159059725", |
| 18 | + name="The Definitive Guide to Django: Web Development Done Right", |
| 19 | + pages=447, |
| 20 | + rating=4.5, |
| 21 | + price=Decimal("30.00"), |
| 22 | + contact=cls.a1, |
| 23 | + pubdate=datetime.date(2007, 12, 6), |
| 24 | + ) |
| 25 | + cls.b2 = Book.objects.create( |
| 26 | + isbn="067232959", |
| 27 | + name="Sams Teach Yourself Django in 24 Hours", |
| 28 | + pages=528, |
| 29 | + rating=3.0, |
| 30 | + price=Decimal("30.00"), |
| 31 | + contact=cls.a2, |
| 32 | + pubdate=datetime.date(2008, 3, 3), |
| 33 | + ) |
| 34 | + cls.b3 = Book.objects.create( |
| 35 | + isbn="159059996", |
| 36 | + name="Practical Django Projects", |
| 37 | + pages=600, |
| 38 | + rating=40.5, |
| 39 | + price=Decimal("30.00"), |
| 40 | + contact=cls.a3, |
| 41 | + pubdate=datetime.date(2008, 6, 23), |
| 42 | + ) |
| 43 | + cls.a1.friends.add(cls.a2) |
| 44 | + cls.a1.friends.add(cls.a3) |
| 45 | + cls.b1.authors.add(cls.a1) |
| 46 | + cls.b1.authors.add(cls.a3) |
| 47 | + cls.b2.authors.add(cls.a2) |
| 48 | + cls.b3.authors.add(cls.a3) |
| 49 | + |
| 50 | + def test_filtered_aggregate_empty_condition_distinct(self): |
| 51 | + book = Book.objects.annotate( |
| 52 | + ages=Count("authors__age", filter=Q(authors__in=[]), distinct=True), |
| 53 | + ).get(pk=self.b1.pk) |
| 54 | + self.assertEqual(book.ages, 0) |
| 55 | + aggregate = Book.objects.aggregate(max_rating=Max("rating", filter=Q(rating__in=[]))) |
| 56 | + self.assertEqual(aggregate, {"max_rating": None}) |
| 57 | + |
| 58 | + def test_filtered_aggregate_full_condition(self): |
| 59 | + book = Book.objects.annotate( |
| 60 | + ages=Count("authors__age", filter=~Q(pk__in=[])), |
| 61 | + ).get(pk=self.b1.pk) |
| 62 | + self.assertEqual(book.ages, 2) |
| 63 | + aggregate = Book.objects.aggregate(max_rating=Max("rating", filter=~Q(rating__in=[]))) |
| 64 | + self.assertEqual(aggregate, {"max_rating": 40.5}) |
| 65 | + |
| 66 | + def test_filtered_aggregate_full_condition_distinct(self): |
| 67 | + book = Book.objects.annotate( |
| 68 | + ages=Count("authors__age", filter=~Q(authors__in=[]), distinct=True), |
| 69 | + ).get(pk=self.b1.pk) |
| 70 | + self.assertEqual(book.ages, 1) |
| 71 | + aggregate = Book.objects.aggregate(max_rating=Max("rating", filter=~Q(rating__in=[]))) |
| 72 | + self.assertEqual(aggregate, {"max_rating": 40.5}) |
0 commit comments