'How can I get the total objects returned in Django queryset within my aggregation?

If I have a model:

class Book(models.Model):
    name = models.CharField(max_length=100)
    ...

And I do a query:

Book.objects.filter(name__icontains="The").aggregate(number_of_books=Count("*"), ...)

Here, I'm filtering the books to only return ones that contain the The substring, and doing an aggregation. I want the resulting dict to tell me, among other things, how many items were in my queryset. This should be the same as if I did Book.objects.filter(name__icontainers="The").count().

What will get me the total number of items (Books) in my queryset? Count("*") was just a guess, but it seems to work. Is that correct?



Solution 1:[1]

Sorry, correct me if I'm wrong, or if you're doing something extra here, but one can simply:

 Book.objects.filter(name__icontains="The").count()

Which returns an integer which is the length of the queryset you've filtered.

.count() isn't heavy on resources, so if you need to have both an aggregated queryset AND the count, just make two queries to the database, one for your count, and the other your aggregated queryset.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Swift