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

1👍

You can do this using a Prefetch object:
https://docs.djangoproject.com/en/1.7/ref/models/querysets/#prefetch-related

e.g.

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