[Fixed]-How to annotate a related object to queryset, in cases it exists, and None otherwise? (Django)


You can do this using a Prefetch object:


seen_qs = Seen.objects.filter(user=request.user)
replies_qs = Reply.objects.prefetch_related(
    Prefetch('seen_set', queryset=seen_qs)

On Django < 1.7 you’ll can do two queries and combine them in the view, e.g.

seen_for = {
    seen.which_reply_id: seen
    for seen in Seen.objects.filter(user=request.user)
replies_qs = Reply.objects.filter(whatever)

# you could attach the Seen instance to each Reply
# or just make a paired list e.g.
replies = [
    (reply, seen_for.get(reply.pk))  # None if not found
    for reply in replies_qs

Leave a comment