I am having a models.py as follows
JavaScript
x
7
1
class Comment(models.Model):
2
auther_name = models.CharField(max_length=20, null=False, blank=False)
3
comment_body = models.TextField(max_length=200, null=False, blank=False)
4
5
class Post(models.Model):
6
comments = models.ManyToManyField(Comment)
7
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).
JavaScript
1
7
1
class Comment(models.Model):
2
author_name = models.CharField(max_length=20, null=False, blank=False)
3
comment_body = models.TextField(max_length=200, null=False, blank=False)
4
5
class Post(models.Model):
6
comments = models.ManyToManyField(Comment, related_name='posts')
7
Now you can do:
JavaScript
1
3
1
for post in Comment.objects.get(pk=12).posts.all():
2
print(post.xxx)
3