Reputation: 58
Post model
class Post(models.Model):
likes = models.ManyToManyField(User, related_name="liked_by", blank=True)
I am trying to query all posts that are liked by a particular user but I couldn't find the right __ query for it. This is the query I'm trying to make.
Post.objects.filter(likes__liked_by=User.objects.get(pk=1))
How can I achieve that?
Upvotes: 0
Views: 668
Reputation: 305
You probably want to look at it the opposite way so go through the
User.objects.get(pk=1).liked_by.all()
Upvotes: 1
Reputation: 71
You can use the prefetch_related
and perform query as the below one.
User.objects.prefetch_related('liked_by').get(pk=1).liked_by.all()
Upvotes: 1