Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django annotate queryset depending on another query

class TradeItem(models.Model):
    ...

class Wishlist(models.Model):
    user = models.ForeignKey(User, related_name='wishlist_user')
    item = models.ForeignKey(TradeItem, related_name='wishlist_item')

I need to make TradeItem queryset annotated with a Boolean of whether an item is in this user's wishlist. Something like

items = TradeItem.objects.all().annotate(wishlist=
 <heresy>
 if Wishlist.objects.filter(user=request.user, item={current_item}: 
  True 
 else: 
  False
 </heresy>
 )

Is it possible to do the said thing with annotate/aggregate, and what would be the most efficient way for that in general?

like image 396
Vémundr Avatar asked Apr 25 '26 13:04

Vémundr


1 Answers

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...

like image 127
webtweakers Avatar answered Apr 27 '26 01:04

webtweakers