Home > Net >  check user have liked msg or not from list of messages
check user have liked msg or not from list of messages

Time:09-21

suppose

class Msg(models.Model):
    ...
    likes = models.ManyToManyField(User,...)
    channelname = models.CharField(...)

Now my queryset is

queryset = Msg.objects.filter(channelname='home')

What should i do after this to get somelike

[{id:xyz,liked=true},{id:tuv,liked=true},{id:abc,liked:false}]

CodePudding user response:

You can annotate an Exists() subquery using the through model of your many to many field:

from django.db.models import Exists, OuterRef


liked_subquery = Msg.likes.through.objects.filter(
    msg=OuterRef('pk'),  # Filter for outer queries Msg instance
    user=some_user_instance  # Filter for user whose like we are checking for
)
queryset = Msg.objects.filter(
    channelname='home'
).annotate(
    liked=Exists(liked_subquery)
).values('id', 'liked')

print(list(queryset))
  • Related