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?
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With