[Answered ]-Count(*) as in Django Orm

1👍

For example if you have “Book” object just cast .count() method:

Book.objects.count()

1👍

Suppose you want to do an aggregation. Django ORM can do it. Here is a documentation.

In short, you can aggregate some count and then use it in you query. Example from documentation:

class Author(models.Model):
   name = models.CharField(max_length=100)
   age = models.IntegerField()

class Publisher(models.Model):
   name = models.CharField(max_length=300)
   num_awards = models.IntegerField()

class Book(models.Model):
   name = models.CharField(max_length=300)
   pages = models.IntegerField()
   price = models.DecimalField(max_digits=10, decimal_places=2)
   rating = models.FloatField()
   authors = models.ManyToManyField(Author)
   publisher = models.ForeignKey(Publisher)
   pubdate = models.DateField()

class Store(models.Model):
   name = models.CharField(max_length=300)
   books = models.ManyToManyField(Book)
   registered_users = models.PositiveIntegerField()

Now, when you do this:

>>> from django.db.models import Count
>>> pubs = Publisher.objects.annotate(num_books=Count('book'))
>>> pubs

SQL query will be the following:

SELECT "main_publisher"."id", "main_publisher"."name", "main_publisher"."num_awards", COUNT("main_book"."id") AS "num_books" FROM "main_publisher"LEFT OUTER JOIN "main_book" ON ("main_publisher"."id" = "main_book"."publisher_id") GROUP BY "main_publisher"."id", "main_publisher"."name", "main_publisher"."num_awards" LIMIT 21; args=()

And you can use aggregated data in filtering:

>>> pubs = Publisher.objects.annotate(num_books=Count('book')).filter(num_books=2)
>>> pubs

SELECT "main_publisher"."id", "main_publisher"."name", "main_publisher"."num_awards", COUNT("main_book"."id") AS "num_books" FROM "main_publisher"LEFT OUTER JOIN "main_book" ON ("main_publisher"."id" = "main_book"."publisher_id") GROUP BY "main_publisher"."id", "main_publisher"."name", "main_publisher"."num_awards" HAVING COUNT("main_book"."id") = 2  LIMIT 21; args=(2,)
👤stalk

Leave a comment