python - 如何获取某个主题的最新帖子?
问题描述
在表格中,我想显示该主题的最新帖子。我的帖子模型称为帖子。我在下面列出了我的代码。
论坛.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})
如果您需要更多详细信息,请告诉我。
谢谢,
卡梅伦。
解决方案
要获取最新主题,您可以执行以下操作,
latest_topic = Topic.objects.order_by('-createtime')[-1]
或者
latest_topic = Topic.objects.order_by('-id')[-1]
推荐阅读
- ffmpeg - ffmpeg 计时元数据值与 ffprobe 输出不同
- c - fgets() 没有得到输入
- javascript - Javascript按日期字段对数组进行排序
- javascript - 如何从 Angular 11 组件访问 chrome api
- sql - sqlite 从 group by 中获取总行数
- vue.js - Gridsome / Vue 上的 Tailwind 配置背景图像路径
- ios - 从 xcodebuild 命令导出存档时抛出配置文件需要错误
- opencv - 找到二维点之间的最大圆拟合
- firebase - Flutter 两次之间的时间?
- date - 在不解析子字符串的情况下在 SSIS 中与日期保持一致