首页 > 解决方案 > 如何获取某个主题的最新帖子?

问题描述

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

论坛.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 %}

视图.py:

def forums(request):
    categories = Category.objects.all()
    topics = Topic.objects.all()
    return render(request, 'forum.html', {'categories': categories, 'topics': topics})

如果您需要更多详细信息,请告诉我。

谢谢,

卡梅伦。

标签: pythondjango

解决方案


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

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

或者

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

推荐阅读