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
CodePudding user response:
In the template, you can render this as:
{% for message in object.message_set.all %} {{ message.body }} {% endfor %}
This will thus, for the Post
object in the context named object
retrieve all the related Message
s.
If you want to fetch the data of the related user as well, you can work with a Prefetch
object [Django-doc]:
from django.db.models import Prefetch
class PostDetailView(DetailView):
model = Post
queryset = Post.objects.prefetch_related(
Prefetch('message_set', Message.objects.select_related('user'))
)
Note: It is normally better to make use of the
settings.AUTH_USER_MODEL
[Django-doc] to refer to the user model, than to use theUser
model [Django-doc] directly. For more information you can see the referencing theUser
model section of the documentation.
Note: Django's
DateTimeField
[Django-doc] has aauto_now_add=…
parameter [Django-doc] to work with timestamps. This will automatically assign the current datetime when creating the object, and mark it as non-editable (editable=False
), such that it does not appear inModelForm
s by default.