Skip to content
Advertisement

Accessing Parent Model from child element of ManyToManyField (Django)

I am having a models.py as follows

class Comment(models.Model):
    auther_name = models.CharField(max_length=20, null=False, blank=False)
    comment_body = models.TextField(max_length=200, null=False, blank=False)

class Post(models.Model):
    comments = models.ManyToManyField(Comment)

So let’s say i have a comment Object Instance which’s id is 2 and raw content

How to get parent post_id which contains this comment??

Advertisement

Answer

Use related_name. Small change adding: related_name='posts': think of it like “if we start from the opposite side, what would be the name to use” (it’s always plural).

class Comment(models.Model):
    author_name = models.CharField(max_length=20, null=False, blank=False)
    comment_body = models.TextField(max_length=200, null=False, blank=False)

class Post(models.Model):
    comments = models.ManyToManyField(Comment, related_name='posts')

Now you can do:

for post in Comment.objects.get(pk=12).posts.all():
    print(post.xxx)
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement