如何在 Django 上使用 DetailView 显示消息

How to show messages using DetailView on Django

我有消息模型和 Post 模型。

我想显示 post 发送给一个 post 的所有消息。

我想不出如何使用 DetailView Class 在某个 post 获取所有消息。

我该怎么做?或者我应该为消息创建另一个 ListView Class?

All my code

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

在模板中,您可以将其呈现为:

{% for message in object.message_set.all %}
    {{ message.body }}
{% endfor %}

因此,对于名为 object 的上下文中的 Post 对象,这将检索所有相关的 Messages。

如果您还想获取相关用户的数据,您可以使用 Prefetch object [Django-doc]:

from django.db.models import Prefetch

class PostDetailView(DetailView):
    model = Post
    queryset = Post.objects.prefetch_related(
        <strong>Prefetch(</strong>'message_set', Message.objects<strong>.select_related('user'))</strong>
    )

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 the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.


Note: Django's DateTimeField [Django-doc] has a auto_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 in ModelForms by default.