[Django]-Django: Reference to an outer query may only be used in a subquery

19👍

The problem is that .count() is something that evaluates the query eagerly, and thus Subquery(..) is never used. But even if that would work, it is not a good idea to do so anyway.

You can just count with a JOIN, like:

from django.db.models import Count, Exists, OuterRef

def get_queryset(self):
    posts = Post.objects.filter(topic_id=OuterRef('pk'))
    unread_posts = posts.exclude(read_by=self.request.user)
    return Topic.objects.annotate(
        is_unread=Exists(unread_posts),
        number_of_replies=Count('post')
    ).order_by('-latest_post')

Leave a comment