Simple Subquery with OuterRef

One of the problems with your example is that you cannot use queryset.count() as a subquery, because .count() tries to evaluate the queryset and return the count. So one may think that the right approach would be to use Count() instead. Maybe something like this: Post.objects.annotate( count=Count(Tag.objects.filter(post=OuterRef(‘pk’))) ) This won’t work for two reasons: The … Read more

aggregate() vs annotate() in Django

I would focus on the example queries rather than your quote from the documentation. Aggregate calculates values for the entire queryset. Annotate calculates summary values for each item in the queryset. Aggregation >>> Book.objects.aggregate(average_price=Avg(‘price’)) {‘average_price’: 34.35} Returns a dictionary containing the average price of all books in the queryset. Annotation >>> q = Book.objects.annotate(num_authors=Count(‘authors’)) >>> … Read more