从 ManyToManyField (Django) 的子元素访问父模型

Accessing Parent Model from child element of ManyToManyField (Django)

我有一个 models.py 如下


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)

假设我有一个 id 为 2 和原始内容的评论对象实例

如何获取包含此评论的父 post_id?

使用related_name。小改动添加:related_name='posts':把它想象成“如果我们从另一边开始,使用什么名字”(它总是复数)。

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')

现在您可以:

for post in Comment.objects.get(pk=12).posts.all():
    print(post.xxx)