I am creating a blogging website. I want to display all the articles posted by any particular writer/user. I have created the 'Post' model as the child of the 'Writer' model. I wanna display all the articles of the user in his profile. But I can't access the Post('s title) from the parent class, ie, Writer class. (I searched a few answers from the internet. Didn't help.) I am getting the error: 'Writer' object has no attribute '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'
The name of the relation in reverse is specified by the related_name=…
parameter [Django-doc] . Since you wrote:
post_writer = models.ForeignKey(
Writer, null=True, ,
related_query_name='tag', on_delete=models.CASCADE
)
it means you access these with:
def profile(request, pk):
writer = Writer.objects.get(id=pk)
print(writer..all())
But it looks rather odd to specify this as tags
/ tag
in the first place. Why not use related_name='posts'
?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.