我正在创建一个博客网站。我想显示任何特定作者/用户发布的所有文章。我已经创建了“ Post”模型作为“ Writer”模型的子模型。我想在用户个人资料中显示该用户的所有文章。但是我无法从父类(即Writer类)访问Post(的标题)。 (我从互联网上搜索了一些答案。没有帮助。)我收到错误消息:“作家”对象没有属性“ post_set”
class Writer(models.Model):
user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE)
email = models.EmailField(unique=True)
profile_pic = models.ImageField(default='profile.png', upload_to = 'Bloggers')
def __str__(self):
return self.user.username
class Post(models.Model):
title = models.CharField(max_length=25)
cover = models.ImageField(upload_to='Blog Image')
content = models.TextField()
post_writer = models.ForeignKey(Writer,null=True, related_name="tags", related_query_name="tag", on_delete=models.CASCADE)
def __str__(self):
return self.title
def profile(request, pk):
writer = Writer.objects.get(id=pk)
print(writer.post_set.all())
'Writer' object has no attribute 'post_set'
答案 0 :(得分:1)
反向关系的名称由related_name=…
parameter [Django-doc]指定。自从您写过:
post_writer = models.ForeignKey(
Writer, null=True, related_name='tags',
related_query_name='tag', on_delete=models.CASCADE
)
这意味着您可以通过以下方式访问它们:
def profile(request, pk):
writer = Writer.objects.get(id=pk)
print(writer.tags.all())
但是首先将其指定为tags
/ tag
看起来很奇怪。为什么不使用related_name='posts'
?