Search code examples
pythondjangodjango-modelsmany-to-many

access to related_name in ManyToManyField from it's model


This is my model:

class Post(models.Model):
    like = models.ManyToManyField(User, blank=True, related_name="likes", symmetrical=False)

I want to show how many poeple like this post. for do this I need to access to related_name and show count it, but related_name just work with ForiegnKey.

I test these and don't worked:

post.like.likes.count()
post.like.user_set.count()

Django: v4.0.1


Solution

  • related_name it's name of reverse relation. For example like.likes.all() will return all Post object.

    You can check how many people like this post by this post.like.count()

    BTW. In this example you set related_name to posts