Ad

Access To Related_name In ManyToManyField From It's Model

- 1 answer

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

Ad

Answer

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

Ad
source: stackoverflow.com
Ad