I have Message model and Post model.
I want to show all messages which posted to one post.
I can't think of how to get all messages at certain post using DetailView Class.
How can I do this? or should I create another ListView Class for messages?
models.py
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User,on_delete=models.CASCADE)
topic = models.ForeignKey(Topic,on_delete=models.SET_NULL,null=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post-detail',kwargs={'pk':self.pk})
class Message(models.Model):
user = models.ForeignKey(User,on_delete=models.CASCADE)
post = models.ForeignKey(Post,on_delete=models.CASCADE)
body = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.body[0:50]
views.py
class PostDetailView(DetailView):
model = Post
In the template, you can render this as:
{% for message in object.message_set.all %} {{ message.body }} {% endfor %}This will thus, for the
Postobject in the context namedobjectretrieve all the relatedMessages.If you want to fetch the data of the related user as well, you can work with a
Prefetchobject [Django-doc]: