django.db.models.Sum - python examples

Here are the examples of the python api django.db.models.Sum taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

145 Examples 7

3 View Complete Implementation : daily_spent_time_loader.py
Copyright MIT License
Author : diegojromerolopez
@register.filter
def total_time_difference(daily_spent_times):
    spent_time_sum = daily_spent_times.aggregate(sum=Sum("spent_time"))["sum"]
    estimated_time_sum = daily_spent_times.aggregate(sum=Sum("estimated_time"))["sum"]
    if spent_time_sum and estimated_time_sum:
        return estimated_time_sum - spent_time_sum
    return None

3 View Complete Implementation : serializers.py
Copyright GNU Affero General Public License v3.0
Author : adfinis-sygroup
    def get_root_meta(self, resource, many):
        if not many:
            queryset = Report.objects.filter(task__project=self.instance)
            data = queryset.aggregate(spent_time=Sum("duration"))
            data["spent_time"] = duration_string(data["spent_time"] or timedelta(0))
            return data

        return {}

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_annotation_expressions(self):
        authors = Author.objects.annotate(combined_ages=Sum(F('age') + F('friends__age'))).order_by('name')
        authors2 = Author.objects.annotate(combined_ages=Sum('age') + Sum('friends__age')).order_by('name')
        for qs in (authors, authors2):
            self.astertQuerysetEqual(
                qs, [
                    ('Adrian Holovaty', 132),
                    ('Brad Dayley', None),
                    ('Jacob Kaplan-Moss', 129),
                    ('James Bennett', 63),
                    ('Jeffrey Forcier', 128),
                    ('Paul Bissex', 120),
                    ('Peter Norvig', 103),
                    ('Stuart Russell', 103),
                    ('Wesley J. Chun', 176)
                ],
                lambda a: (a.name, a.combined_ages)
            )

3 View Complete Implementation : models.py
Copyright MIT License
Author : diegojromerolopez
    @staticmethod
    def _sum_spent_time(daily_spent_times):
        spent_time = daily_spent_times. \
            aggregate(sum=Sum("spent_time"))["sum"]
        if spent_time is None:
            return 0
        return spent_time

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_filter_agg_with_double_f(self):
        books = Book.objects.annotate(
            sum_rating=Sum('rating')
        ).filter(sum_rating=F('sum_rating'))
        for book in books:
            self.astertEqual(book.sum_rating, book.rating)

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_decimal_max_digits_has_no_effect(self):
        Book.objects.all().delete()
        a1 = Author.objects.first()
        p1 = Publisher.objects.first()
        thedate = timezone.now()
        for i in range(10):
            Book.objects.create(
                isbn="abcde{}".format(i), name="none", pages=10, rating=4.0,
                price=9999.98, contact=a1, publisher=p1, pubdate=thedate)

        book = Book.objects.aggregate(price_sum=Sum('price'))
        self.astertEqual(book['price_sum'], Decimal("99999.80"))

3 View Complete Implementation : api.py
Copyright MIT License
Author : learningequality
def num_correct(examlog):
    return (
        examlog.attemptlogs.values_list("item", "content_id")
        .order_by("completion_timestamp")
        .distinct()
        .aggregate(Sum("correct"))
        .get("correct__sum")
    )

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_annotate_values_aggregate(self):
        alias_age = Author.objects.annotate(
            age_alias=F('age')
        ).values(
            'age_alias',
        ).aggregate(sum_age=Sum('age_alias'))

        age = Author.objects.values('age').aggregate(sum_age=Sum('age'))

        self.astertEqual(alias_age['sum_age'], age['sum_age'])

3 View Complete Implementation : serializers.py
Copyright GNU Affero General Public License v3.0
Author : adfinis-sygroup
    def get_purchased_time(self, obj):
        """
        Calculate purchased time for given project.

        Only acknowledged hours are included.
        """
        orders = Order.objects.filter(project=obj, acknowledged=True)
        data = orders.aggregate(purchased_time=Sum("duration"))
        return duration_string(data["purchased_time"] or timedelta(0))

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_annotation_expressions(self):
        authors = Author.objects.annotate(combined_ages=Sum(F('age') + F('friends__age'))).order_by('name')
        authors2 = Author.objects.annotate(combined_ages=Sum('age') + Sum('friends__age')).order_by('name')
        for qs in (authors, authors2):
            self.astertQuerysetEqual(
                qs, [
                    ('Adrian Holovaty', 132),
                    ('Brad Dayley', None),
                    ('Jacob Kaplan-Moss', 129),
                    ('James Bennett', 63),
                    ('Jeffrey Forcier', 128),
                    ('Paul Bissex', 120),
                    ('Peter Norvig', 103),
                    ('Stuart Russell', 103),
                    ('Wesley J. Chun', 176)
                ],
                lambda a: (a.name, a.combined_ages)
            )

3 View Complete Implementation : 0064_auto_20170402_2123.py
Copyright MIT License
Author : diegojromerolopez
def set_number_of_mentioned_members(apps, schema):
    Card = apps.get_model("boards", "Card")
    CardComment = apps.get_model("boards", "CardComment")
    cards = Card.objects.all()
    for card in cards:
        card.number_of_mentioned_members = CardComment.objects.filter(card=card).\
            aggregate(num_mentions=Sum("number_of_mentioned_members")).get("num_mentions", 0)
        if card.number_of_mentioned_members is None:
            card.number_of_mentioned_members = 0
        card.save()

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_complex_aggregations_require_kwarg(self):
        with self.astertRaisesMessage(TypeError, 'Complex annotations require an alias'):
            Author.objects.annotate(Sum(F('age') + F('friends__age')))
        with self.astertRaisesMessage(TypeError, 'Complex aggregates require an alias'):
            Author.objects.aggregate(Sum('age') / Count('age'))
        with self.astertRaisesMessage(TypeError, 'Complex aggregates require an alias'):
            Author.objects.aggregate(Sum(1))

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_annotate_defer_select_related(self):
        qs = Book.objects.select_related('contact').annotate(
            page_sum=Sum("pages")).defer('name').filter(pk=self.b1.pk)

        rows = [
            (self.b1.id, "159059725", 447, "Adrian Holovaty",
             "The Definitive Guide to Django: Web Development Done Right")
        ]
        self.astertQuerysetEqual(
            qs.order_by('pk'), rows,
            lambda r: (r.id, r.isbn, r.page_sum, r.contact.name, r.name)
        )

3 View Complete Implementation : models.py
Copyright MIT License
Author : diegojromerolopez
    @property
    def done_cards_spent_time(self):
        done_cards_spent_time = self.done_cards.aggregate(sum=Sum("spent_time"))["sum"]
        if done_cards_spent_time is None:
            return 0
        return done_cards_spent_time

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_annotate_defer(self):
        qs = Book.objects.annotate(
            page_sum=Sum("pages")).defer('name').filter(pk=self.b1.pk)

        rows = [
            (self.b1.id, "159059725", 447, "The Definitive Guide to Django: Web Development Done Right")
        ]
        self.astertQuerysetEqual(
            qs.order_by('pk'), rows,
            lambda r: (r.id, r.isbn, r.page_sum, r.name)
        )

3 View Complete Implementation : models.py
Copyright GNU Affero General Public License v3.0
Author : adfinis-sygroup
    def calculate_credit(self, user, start, end):
        """
        Calculate approved days of type for user in given time frame.

        For absence types which fill worktime this will be None.
        """
        if self.fill_worktime:
            return None

        credits = AbsenceCredit.objects.filter(
            user=user, absence_type=self, date__range=[start, end]
        )
        data = credits.aggregate(credit=Sum("days"))
        credit = data["credit"] or 0

        return credit

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_annotate_values_aggregate(self):
        alias_age = Author.objects.annotate(
            age_alias=F('age')
        ).values(
            'age_alias',
        ).aggregate(sum_age=Sum('age_alias'))

        age = Author.objects.values('age').aggregate(sum_age=Sum('age'))

        self.astertEqual(alias_age['sum_age'], age['sum_age'])

3 View Complete Implementation : serializers.py
Copyright MIT License
Author : learningequality
    def get_score(self, obj):
        return (
            obj.attemptlogs.values_list("item")
            .order_by("completion_timestamp")
            .distinct()
            .aggregate(Sum("correct"))
            .get("correct__sum")
        )

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_sum_distinct_aggregate(self):
        """
        Sum on a distinct() QuerySet should aggregate only the distinct items.
        """
        authors = Author.objects.filter(book__in=[self.b5, self.b6])
        self.astertEqual(authors.count(), 3)

        distinct_authors = authors.distinct()
        self.astertEqual(distinct_authors.count(), 2)

        # Selected author ages are 57 and 46
        age_sum = distinct_authors.aggregate(Sum('age'))
        self.astertEqual(age_sum['age__sum'], 103)

3 View Complete Implementation : api.py
Copyright MIT License
Author : agstrike
@login_required
def category_spending(request, dstart, dend):
    try:
        dstart = datetime.datetime.strptime(dstart, '%Y-%m-%d')
        dend = datetime.datetime.strptime(dend, '%Y-%m-%d')
    except ValueError:
        return HttpResponseBadRequest(_('Invalid date format, expected yyyy-mm-dd'))
    res = Split.objects.expense().past().date_range(dstart, dend).order_by('category').values(
        'category__name').annotate(spent=models.Sum('amount'))
    if res:
        res = [(e['category__name'] or 'No category', abs(e['spent'])) for e in res if e['spent']]
        categories, spent = zip(*res)
    else:
        categories, spent = [], []
    return JsonResponse({'categories': categories, 'spent': spent})

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_filter_agg_with_double_f(self):
        books = Book.objects.annotate(
            sum_rating=Sum('rating')
        ).filter(sum_rating=F('sum_rating'))
        for book in books:
            self.astertEqual(book.sum_rating, book.rating)

3 View Complete Implementation : test_filter_argument.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_case_aggregate(self):
        agg = Sum(
            Case(When(friends__age=40, then=F('friends__age'))),
            filter=Q(friends__name__startswith='test'),
        )
        self.astertEqual(Author.objects.aggregate(age=agg)['age'], 80)

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_annotated_aggregate_over_annotated_aggregate(self):
        with self.astertRaisesMessage(FieldError, "Cannot compute Sum('id__max'): 'id__max' is an aggregate"):
            Book.objects.annotate(Max('id')).annotate(Sum('id__max'))

        clast MyMax(Max):
            def as_sql(self, compiler, connection):
                self.set_source_expressions(self.get_source_expressions()[0:1])
                return super().as_sql(compiler, connection)

        with self.astertRaisesMessage(FieldError, "Cannot compute Max('id__max'): 'id__max' is an aggregate"):
            Book.objects.annotate(Max('id')).annotate(my_max=MyMax('id__max', 'price'))

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_aggregation_expressions(self):
        a1 = Author.objects.aggregate(av_age=Sum('age') / Count('*'))
        a2 = Author.objects.aggregate(av_age=Sum('age') / Count('age'))
        a3 = Author.objects.aggregate(av_age=Avg('age'))
        self.astertEqual(a1, {'av_age': 37})
        self.astertEqual(a2, {'av_age': 37})
        self.astertEqual(a3, {'av_age': Approximate(37.4, places=1)})

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_annotate_defer(self):
        qs = Book.objects.annotate(
            page_sum=Sum("pages")).defer('name').filter(pk=self.b1.pk)

        rows = [
            (self.b1.id, "159059725", 447, "The Definitive Guide to Django: Web Development Done Right")
        ]
        self.astertQuerysetEqual(
            qs.order_by('pk'), rows,
            lambda r: (r.id, r.isbn, r.page_sum, r.name)
        )

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_complex_aggregations_require_kwarg(self):
        with self.astertRaisesMessage(TypeError, 'Complex annotations require an alias'):
            Author.objects.annotate(Sum(F('age') + F('friends__age')))
        with self.astertRaisesMessage(TypeError, 'Complex aggregates require an alias'):
            Author.objects.aggregate(Sum('age') / Count('age'))
        with self.astertRaisesMessage(TypeError, 'Complex aggregates require an alias'):
            Author.objects.aggregate(Sum(1))

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_aggregation_expressions(self):
        a1 = Author.objects.aggregate(av_age=Sum('age') / Count('*'))
        a2 = Author.objects.aggregate(av_age=Sum('age') / Count('age'))
        a3 = Author.objects.aggregate(av_age=Avg('age'))
        self.astertEqual(a1, {'av_age': 37})
        self.astertEqual(a2, {'av_age': 37})
        self.astertEqual(a3, {'av_age': Approximate(37.4, places=1)})

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_annotation_in_f_grouped_by_annotation(self):
        qs = (
            Publisher.objects.annotate(multiplier=Value(3))
            # group by option => sum of value * multiplier
            .values('name')
            .annotate(multiplied_value_sum=Sum(F('multiplier') * F('num_awards')))
            .order_by()
        )
        self.astertCountEqual(
            qs, [
                {'multiplied_value_sum': 9, 'name': 'Apress'},
                {'multiplied_value_sum': 0, 'name': "Jonno's House of Books"},
                {'multiplied_value_sum': 27, 'name': 'Morgan Kaufmann'},
                {'multiplied_value_sum': 21, 'name': 'Prentice Hall'},
                {'multiplied_value_sum': 3, 'name': 'Sams'},
            ]
        )

3 View Complete Implementation : serializers.py
Copyright MIT License
Author : learningequality
def get_topic_progress_fraction(topic, user):
    leaf_ids = (
        topic.get_descendants(include_self=False)
        .order_by()
        .exclude(kind=content_kinds.TOPIC)
        .values_list("content_id", flat=True)
    )
    return round(
        (
            get_summary_logs(leaf_ids, user).aggregate(Sum("progress"))["progress__sum"]
            or 0
        )
        / (len(leaf_ids) or 1),
        4,
    )

3 View Complete Implementation : test_functions.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @skipUnlessDBFeature("has_Area_function")
    def test_area_with_regular_aggregate(self):
        # Create projected country objects, for this test to work on all backends.
        for c in Country.objects.all():
            CountryWebMercator.objects.create(name=c.name, mpoly=c.mpoly.transform(3857, clone=True))
        # Test in projected coordinate system
        qs = CountryWebMercator.objects.annotate(area_sum=Sum(functions.Area('mpoly')))
        # Some backends (e.g. Oracle) cannot group by multipolygon values, so
        # defer such fields in the aggregation query.
        for c in qs.defer('mpoly'):
            result = c.area_sum
            # If the result is a measure object, get value.
            if isinstance(result, Area):
                result = result.sq_m
            self.astertAlmostEqual((result - c.mpoly.area) / c.mpoly.area, 0)

3 View Complete Implementation : 0071_auto_20170530_1711.py
Copyright MIT License
Author : diegojromerolopez
def set_card_adjusted_spent_time(apps, schema):
    Card = apps.get_model("boards", "Card")
    for card in Card.objects.all():
        card_adjusted_spent_time = card.daily_spent_times.all().\
            aggregate(adj_spent_time_sum=Sum("adjusted_spent_time"))["adj_spent_time_sum"]
        card.adjusted_spent_time = card_adjusted_spent_time
        card.save()

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_related_aggregate(self):
        vals = Author.objects.aggregate(Avg("friends__age"))
        self.astertEqual(vals, {'friends__age__avg': Approximate(34.07, places=2)})

        vals = Book.objects.filter(rating__lt=4.5).aggregate(Avg("authors__age"))
        self.astertEqual(vals, {'authors__age__avg': Approximate(38.2857, places=2)})

        vals = Author.objects.all().filter(name__contains="a").aggregate(Avg("book__rating"))
        self.astertEqual(vals, {'book__rating__avg': 4.0})

        vals = Book.objects.aggregate(Sum("publisher__num_awards"))
        self.astertEqual(vals, {'publisher__num_awards__sum': 30})

        vals = Publisher.objects.aggregate(Sum("book__price"))
        self.astertEqual(vals, {'book__price__sum': Decimal('270.27')})

3 View Complete Implementation : import_export_content.py
Copyright MIT License
Author : learningequality
def calculate_files_to_transfer(nodes_to_include, available):
    files_to_transfer = LocalFile.objects.filter(
        available=available, files__contentnode__in=nodes_to_include
    )

    # Make sure the files are unique, to avoid duplicating downloads
    files_to_transfer = files_to_transfer.distinct()

    # calculate the total file sizes across all files being returned in the queryset
    total_bytes_to_transfer = (
        files_to_transfer.aggregate(Sum("file_size"))["file_size__sum"] or 0
    )

    return files_to_transfer, total_bytes_to_transfer

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_combine_different_types(self):
        msg = 'Expression contains mixed types. You must set output_field.'
        qs = Book.objects.annotate(sums=Sum('rating') + Sum('pages') + Sum('price'))
        with self.astertRaisesMessage(FieldError, msg):
            qs.first()
        with self.astertRaisesMessage(FieldError, msg):
            qs.first()

        b1 = Book.objects.annotate(sums=Sum(F('rating') + F('pages') + F('price'),
                                   output_field=IntegerField())).get(pk=self.b4.pk)
        self.astertEqual(b1.sums, 383)

        b2 = Book.objects.annotate(sums=Sum(F('rating') + F('pages') + F('price'),
                                   output_field=FloatField())).get(pk=self.b4.pk)
        self.astertEqual(b2.sums, 383.69)

        b3 = Book.objects.annotate(sums=Sum(F('rating') + F('pages') + F('price'),
                                   output_field=DecimalField())).get(pk=self.b4.pk)
        self.astertEqual(b3.sums, Approximate(Decimal("383.69"), places=2))

3 View Complete Implementation : api.py
Copyright MIT License
Author : learningequality
    @list_route(methods=["get"])
    def node_astessments(self, request):
        ids = self.request.query_params.get("ids", "").split(",")
        data = 0
        if ids and ids[0]:
            nodes = (
                models.ContentNode.objects.filter_by_uuids(ids)
                .filter(available=True)
                .prefetch_related("astessmentmetadata")
            )
            data = (
                nodes.aggregate(Sum("astessmentmetadata__number_of_astessments"))[
                    "astessmentmetadata__number_of_astessments__sum"
                ]
                or 0
            )
        return Response(data)

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_sum_distinct_aggregate(self):
        """
        Sum on a distinct() QuerySet should aggregate only the distinct items.
        """
        authors = Author.objects.filter(book__in=[self.b5, self.b6])
        self.astertEqual(authors.count(), 3)

        distinct_authors = authors.distinct()
        self.astertEqual(distinct_authors.count(), 2)

        # Selected author ages are 57 and 46
        age_sum = distinct_authors.aggregate(Sum('age'))
        self.astertEqual(age_sum['age__sum'], 103)

3 View Complete Implementation : serializers.py
Copyright GNU Affero General Public License v3.0
Author : adfinis-sygroup
    def get_spent_time(self, obj):
        """
        Calculate spent time for given project.

        Reports which are not billable or are in review are excluded.
        """
        reports = Report.objects.filter(
            task__project=obj, not_billable=False, review=False
        )
        data = reports.aggregate(spent_time=Sum("duration"))
        return duration_string(data["spent_time"] or timedelta())

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_annotate_over_annotate(self):
        author = Author.objects.annotate(
            age_alias=F('age')
        ).annotate(
            sum_age=Sum('age_alias')
        ).get(name="Adrian Holovaty")

        other_author = Author.objects.annotate(
            sum_age=Sum('age')
        ).get(name="Adrian Holovaty")

        self.astertEqual(author.sum_age, other_author.sum_age)

3 View Complete Implementation : serializers.py
Copyright MIT License
Author : learningequality
    def get_progress(self, obj):
        return (
            obj.contentsummarylog_set.filter(progress=1)
            .aggregate(Sum("progress"))
            .get("progress__sum")
        )

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_annotation_in_f_grouped_by_annotation(self):
        qs = (
            Publisher.objects.annotate(multiplier=Value(3))
            # group by option => sum of value * multiplier
            .values('name')
            .annotate(multiplied_value_sum=Sum(F('multiplier') * F('num_awards')))
            .order_by()
        )
        self.astertCountEqual(
            qs, [
                {'multiplied_value_sum': 9, 'name': 'Apress'},
                {'multiplied_value_sum': 0, 'name': "Jonno's House of Books"},
                {'multiplied_value_sum': 27, 'name': 'Morgan Kaufmann'},
                {'multiplied_value_sum': 21, 'name': 'Prentice Hall'},
                {'multiplied_value_sum': 3, 'name': 'Sams'},
            ]
        )

3 View Complete Implementation : annotation.py
Copyright MIT License
Author : learningequality
def total_file_size(files_or_nodes):
    if issubclast(files_or_nodes.model, LocalFile):
        localfiles = files_or_nodes
    elif issubclast(files_or_nodes.model, ContentNode):
        localfiles = files_for_nodes(files_or_nodes)
    else:
        raise TypeError("Expected queryset for LocalFile or ContentNode")
    return localfiles.distinct().aggregate(Sum("file_size"))["file_size__sum"] or 0

3 View Complete Implementation : test_functions.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @skipUnlessDBFeature("has_Area_function")
    def test_area_with_regular_aggregate(self):
        # Create projected country objects, for this test to work on all backends.
        for c in Country.objects.all():
            CountryWebMercator.objects.create(name=c.name, mpoly=c.mpoly.transform(3857, clone=True))
        # Test in projected coordinate system
        qs = CountryWebMercator.objects.annotate(area_sum=Sum(functions.Area('mpoly')))
        # Some backends (e.g. Oracle) cannot group by multipolygon values, so
        # defer such fields in the aggregation query.
        for c in qs.defer('mpoly'):
            result = c.area_sum
            # If the result is a measure object, get value.
            if isinstance(result, Area):
                result = result.sq_m
            self.astertAlmostEqual((result - c.mpoly.area) / c.mpoly.area, 0)

3 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : adfinis-sygroup
    def get_queryset(self):
        queryset = Report.objects.all()

        queryset = queryset.values("task")
        queryset = queryset.annotate(duration=Sum("duration"))
        queryset = queryset.annotate(pk=F("task"))

        return queryset

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_decimal_max_digits_has_no_effect(self):
        Book.objects.all().delete()
        a1 = Author.objects.first()
        p1 = Publisher.objects.first()
        thedate = timezone.now()
        for i in range(10):
            Book.objects.create(
                isbn="abcde{}".format(i), name="none", pages=10, rating=4.0,
                price=9999.98, contact=a1, publisher=p1, pubdate=thedate)

        book = Book.objects.aggregate(price_sum=Sum('price'))
        self.astertEqual(book['price_sum'], Decimal("99999.80"))

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_combine_different_types(self):
        msg = 'Expression contains mixed types. You must set output_field.'
        qs = Book.objects.annotate(sums=Sum('rating') + Sum('pages') + Sum('price'))
        with self.astertRaisesMessage(FieldError, msg):
            qs.first()
        with self.astertRaisesMessage(FieldError, msg):
            qs.first()

        b1 = Book.objects.annotate(sums=Sum(F('rating') + F('pages') + F('price'),
                                   output_field=IntegerField())).get(pk=self.b4.pk)
        self.astertEqual(b1.sums, 383)

        b2 = Book.objects.annotate(sums=Sum(F('rating') + F('pages') + F('price'),
                                   output_field=FloatField())).get(pk=self.b4.pk)
        self.astertEqual(b2.sums, 383.69)

        b3 = Book.objects.annotate(sums=Sum(F('rating') + F('pages') + F('price'),
                                   output_field=DecimalField())).get(pk=self.b4.pk)
        self.astertEqual(b3.sums, Approximate(Decimal("383.69"), places=2))

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_annotate_over_annotate(self):
        author = Author.objects.annotate(
            age_alias=F('age')
        ).annotate(
            sum_age=Sum('age_alias')
        ).get(name="Adrian Holovaty")

        other_author = Author.objects.annotate(
            sum_age=Sum('age')
        ).get(name="Adrian Holovaty")

        self.astertEqual(author.sum_age, other_author.sum_age)

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_annotated_aggregate_over_annotated_aggregate(self):
        with self.astertRaisesMessage(FieldError, "Cannot compute Sum('id__max'): 'id__max' is an aggregate"):
            Book.objects.annotate(Max('id')).annotate(Sum('id__max'))

        clast MyMax(Max):
            def as_sql(self, compiler, connection):
                self.set_source_expressions(self.get_source_expressions()[0:1])
                return super().as_sql(compiler, connection)

        with self.astertRaisesMessage(FieldError, "Cannot compute Max('id__max'): 'id__max' is an aggregate"):
            Book.objects.annotate(Max('id')).annotate(my_max=MyMax('id__max', 'price'))

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_annotate_defer_select_related(self):
        qs = Book.objects.select_related('contact').annotate(
            page_sum=Sum("pages")).defer('name').filter(pk=self.b1.pk)

        rows = [
            (self.b1.id, "159059725", 447, "Adrian Holovaty",
             "The Definitive Guide to Django: Web Development Done Right")
        ]
        self.astertQuerysetEqual(
            qs.order_by('pk'), rows,
            lambda r: (r.id, r.isbn, r.page_sum, r.contact.name, r.name)
        )

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_related_aggregate(self):
        vals = Author.objects.aggregate(Avg("friends__age"))
        self.astertEqual(vals, {'friends__age__avg': Approximate(34.07, places=2)})

        vals = Book.objects.filter(rating__lt=4.5).aggregate(Avg("authors__age"))
        self.astertEqual(vals, {'authors__age__avg': Approximate(38.2857, places=2)})

        vals = Author.objects.all().filter(name__contains="a").aggregate(Avg("book__rating"))
        self.astertEqual(vals, {'book__rating__avg': 4.0})

        vals = Book.objects.aggregate(Sum("publisher__num_awards"))
        self.astertEqual(vals, {'publisher__num_awards__sum': 30})

        vals = Publisher.objects.aggregate(Sum("book__price"))
        self.astertEqual(vals, {'book__price__sum': Decimal('270.27')})

3 View Complete Implementation : test_filter_argument.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_case_aggregate(self):
        agg = Sum(
            Case(When(friends__age=40, then=F('friends__age'))),
            filter=Q(friends__name__startswith='test'),
        )
        self.astertEqual(Author.objects.aggregate(age=agg)['age'], 80)