Python 如何获取某个主题的最新帖子?

Python 如何获取某个主题的最新帖子?,python,django,Python,Django,在表中,我想显示该主题的最新帖子。我的post模型叫做post。我在下面列出了我的代码 forum.html: {% for category in categories %} <h5 class="blue-text">{{ category.title }}</h5> <table> <thead> <tr>

在表中,我想显示该主题的最新帖子。我的post模型叫做post。我在下面列出了我的代码

forum.html:

          {% for category in categories %}
          <h5 class="blue-text">{{ category.title }}</h5>
          <table>
            <thead>
              <tr>
                  <th>Icon</th>
                  <th>Name</th>
                  <th>Latest Post</th>
              </tr>
            </thead>
            {% for topic in category.topic_set.all %}
            <tbody>
              <tr>
                <td><i class="material-icons black-text">{{ topic.icon }}</i></td>
                <td><a href="/forum/topic/{{ topic.slug }}">{{ topic.title }} </a><br> <span class="grey-text">{{ topic.description }}</span></td>
                <td><a href="#!">post_title</a> <br> <span class="grey-text">post_author</span> <br> <span class="grey-text">post_created_at_timesince</span></td>
              </tr>
              {% empty %}
             <p>No topics in {{ category.title }}</p>
            {% endfor %}
            </tbody>
          </table>
         {% empty %}
          <p>No categories.</p>
      {% endfor %}
def forums(request):
    categories = Category.objects.all()
    topics = Topic.objects.all()
    return render(request, 'forum.html', {'categories': categories, 'topics': topics})
如果你需要更多的细节,请告诉我

谢谢


Cameron.

使用
Topic.objects.order_by('-createtime')
按createtime排序。如果您的字段中没有
createtime
,您可以使用
-id
,因为最新主题的id最大。

这可以通过以下方式完成。你可以这样改变你的观点

from django.db.models import Prefetch
def forums(request):
    topics = Topic.objects.all().order_by('-created_time')
    categories = Category.objects.all().prefetch_related(Prefetch('topic_set', queryset=topics)
    return render(request, 'forum.html', {'categories': categories})
上述代码段有两个优点:

  • 当您对category.topic\u set.all%}中的主题执行
    {%操作时,您将获得最新的帖子
  • 不会对模板中的上述语句执行额外的查询
如果您也在其他地方使用,则可以在上下文中添加
主题。对于给定的情况,您不需要在上下文中发送它,因为您是从category对象获取数据的

如果您需要在多个位置获取类别的最新帖子,那么您还可以在
主题
模型的元类中使用
排序
属性


你可以在这里找到更多细节

要获取最新主题,您可以执行以下操作:

latest_topic = Topic.objects.order_by('-createtime')[-1]


这可能会有所帮助:我在视图中输入了错误的部分,但我已经更新了我的答案。我不认为这会起作用,因为它需要在HTML文件中。你应该在你的模型中有一个created_at字段。我在post模型中有这个字段。现在你可以看看这个。不,让我重写我想做的。在表中,我想显示该主题的最新帖子。我的post模型称为post。您不需要
.all()
,也不需要
预回迁
我没有得到的。你能解释一下吗?
latest_topic = Topic.objects.order_by('-id')[-1]