[Answered ]-Accessing Parent Model from child element of ManyToManyField (Django)

1👍

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)

Leave a comment