django.db.models.Count - python examples

Here are the examples of the python api django.db.models.Count 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 : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_grouped_annotation_in_group_by(self):
        """
        An annotation included in values() before an aggregate should be
        included in the group by clause.
        """
        qs = (
            Book.objects.annotate(xprice=F('price')).filter(rating=4.0).values('rating', 'xprice')
                .annotate(count=Count('publisher_id', distinct=True)).values('count', 'rating').order_by('count')
        )
        self.astertEqual(
            list(qs), [
                {'rating': 4.0, 'count': 1},
                {'rating': 4.0, 'count': 2},
            ]
        )

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_complex_values_aggregation(self):
        max_rating = Book.objects.values('rating').aggregate(
            double_max_rating=Max('rating') + Max('rating'))
        self.astertEqual(max_rating['double_max_rating'], 5 * 2)

        max_books_per_rating = Book.objects.values('rating').annotate(
            books_per_rating=Count('id') + 5
        ).aggregate(Max('books_per_rating'))
        self.astertEqual(
            max_books_per_rating,
            {'books_per_rating__max': 3 + 5})

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @skipUnlessDBFeature('allows_group_by_pk')
    def test_rawsql_group_by_collapse(self):
        raw = RawSQL('SELECT MIN(id) FROM annotations_book', [])
        qs = Author.objects.values('id').annotate(
            min_book_id=raw,
            count_friends=Count('friends'),
        ).order_by()
        _, _, group_by = qs.query.get_compiler(using='default').pre_sql_setup()
        self.astertEqual(len(group_by), 1)
        self.astertNotEqual(raw, group_by[0])

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_defer_annotate_select_related(self):
        location = Location.objects.create()
        Request.objects.create(location=location)
        self.astertIsInstance(
            list(Request.objects.annotate(Count('items')).select_related('profile', 'location')
                 .only('profile', 'location')),
            list
        )
        self.astertIsInstance(
            list(Request.objects.annotate(Count('items')).select_related('profile', 'location')
                 .only('profile__profile1', 'location__location1')),
            list
        )
        self.astertIsInstance(
            list(Request.objects.annotate(Count('items')).select_related('profile', 'location')
                 .defer('request1', 'request2', 'request3', 'request4')),
            list
        )

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_update_annotated_multi_table_queryset(self):
        """
        Update of a queryset that's been annotated and involves multiple tables.
        """
        # Trivial annotated update
        qs = DataPoint.objects.annotate(related_count=Count('relatedpoint'))
        self.astertEqual(qs.update(value='Foo'), 3)
        # Update where annotation is used for filtering
        qs = DataPoint.objects.annotate(related_count=Count('relatedpoint'))
        self.astertEqual(qs.filter(related_count=1).update(value='Foo'), 1)
        # Update where annotation is used in update parameters
        # #26539 - This isn't forbidden but also doesn't generate proper SQL
        # qs = RelatedPoint.objects.annotate(data_name=F('data__name'))
        # updated = qs.update(name=F('data_name'))
        # self.astertEqual(updated, 1)
        # Update where aggregation annotation is used in update parameters
        qs = RelatedPoint.objects.annotate(max=Max('data__value'))
        with self.astertRaisesMessage(FieldError, 'Aggregate functions are not allowed in this query'):
            qs.update(name=F('max'))

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_dates_with_aggregation(self):
        """
        .dates() returns a distinct set of dates when applied to a
        QuerySet with aggregation.

        Refs #18056. Previously, .dates() would return distinct (date_kind,
        aggregation) sets, in this case (year, num_authors), so 2008 would be
        returned twice because there are books from 2008 with a different
        number of authors.
        """
        dates = Book.objects.annotate(num_authors=Count("authors")).dates('pubdate', 'year')
        self.astertQuerysetEqual(
            dates, [
                "datetime.date(1991, 1, 1)",
                "datetime.date(1995, 1, 1)",
                "datetime.date(2007, 1, 1)",
                "datetime.date(2008, 1, 1)"
            ]
        )

3 View Complete Implementation : test_expressions.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_multiple_annotation(self):
        multi_field = MultiFields.objects.create(
            point=Point(1, 1),
            city=City.objects.get(name='Houston'),
            poly=Polygon(((1, 1), (1, 2), (2, 2), (2, 1), (1, 1))),
        )
        qs = City.objects.values('name').annotate(
            distance=Min(functions.Distance('multifields__point', multi_field.city.point)),
        ).annotate(count=Count('multifields'))
        self.astertTrue(qs.first())

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_grouped_annotation_in_group_by(self):
        """
        An annotation included in values() before an aggregate should be
        included in the group by clause.
        """
        qs = (
            Book.objects.annotate(xprice=F('price')).filter(rating=4.0).values('rating', 'xprice')
                .annotate(count=Count('publisher_id', distinct=True)).values('count', 'rating').order_by('count')
        )
        self.astertEqual(
            list(qs), [
                {'rating': 4.0, 'count': 1},
                {'rating': 4.0, 'count': 2},
            ]
        )

3 View Complete Implementation : test_expressions.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_multiple_annotation(self):
        multi_field = MultiFields.objects.create(
            point=Point(1, 1),
            city=City.objects.get(name='Houston'),
            poly=Polygon(((1, 1), (1, 2), (2, 2), (2, 1), (1, 1))),
        )
        qs = City.objects.values('name').annotate(
            distance=Min(functions.Distance('multifields__point', multi_field.city.point)),
        ).annotate(count=Count('multifields'))
        self.astertTrue(qs.first())

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_more_aggregation(self):
        a = Author.objects.get(name__contains='Norvig')
        b = Book.objects.get(name__contains='Done Right')
        b.authors.add(a)
        b.save()

        vals = (
            Book.objects
            .annotate(num_authors=Count("authors__id"))
            .filter(authors__name__contains="Norvig", num_authors__gt=1)
            .aggregate(Avg("rating"))
        )
        self.astertEqual(vals, {"rating__avg": 4.25})