[Django]-Django annotate queryset depending on another query

3👍

The problem with this is that annotations are happening on database (SQL) level. You can only make use of functions which are nativly supported by the SQL dialect (like SUM, AVG…). If you want to append an arbitrary attribute/data field you should iterate over the queryset and check this for every instance seperatly:

items = TradeItem.objects.all()
user_wishlist = Wishlist.objects.filter(user=request.user)
for item in items:
    item.wishlist = user_wishlist.filter(item=item).exists()
👤Nerade

4👍

You can actually solve this on database level in a single query, using Exists:

from django.db.models import Exists, OuterRef
user_wishlist = Wishlist.objects.filter(item_id=OuterRef('id'), user=user)
items = TradeItem.objects.annotate(in_wishlist=Exists(user_wishlist))

PS: I know, old question…

Leave a comment