1👍
✅
Without any extra sql, you can just query the related table to see if anything exists like this:\
images = Image.objects.all().prefetch_related('favorited')
for image in images:
image.favorited = image.favorited.filter(user=current_user).exists()
Then you can check image.favorited in the template.
I think a little cleaner way would be to use .extra()
with a little sql. Something like this:
image.objects.extra(select={'favorited': 'EXISTS(SELECT * FROM app_favorite WHERE image_id = app_image.id AND user_id = %s)'}, select_params=[current_user.pk])
Source:stackexchange.com