django - 按降序反转列表以获取 django 模板中的最后一个对象
问题描述
我进行了很多搜索,但找不到任何东西可以按降序反转列表,以便我可以获得模板中每个帖子的最后两条评论。
这是我的模型:
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments')
commented_by = models.ForeignKey(User, on_delete=models.CASCADE)
comment = models.CharField(max_length=128)
视图.py:
posts = Post.objects.all().order_by("date_posted").reverse()
return render(request, "cs50gram/explore.html", {"posts": posts})
模板.html:
{% for post in posts %}
{% for comment in post.comments.all|slice:":2" reversed %}
<div style="color: gray">
<b> {{ comment.commented_by }} </b>
{{ comment.comment }}
</div>
{% endfor %}
{% endfor %}
这里的问题是它先切片然后反转..
我尝试了什么? 如何在 Django 模板中反转 for 循环,然后对结果进行切片
使用答案中提供的解决方案,由于某种原因它不起作用。这正是我在代码中尝试的方式。
{% for post in posts %}
{% for comment in post.comments.all.reverse|slice:":2"%}
<div style="color: gray">
<b> {{ comment.commented_by }} </b>
{{ comment.comment }}
</div>
{% endfor %}
{% endfor %}
输出是它只对它进行切片而不反转。
任何有助于按降序排列列表并获得每个帖子的最后 n (2) 条评论的帮助,我们将不胜感激。
解决方案
您可以使用 order_by('-id') 来获取反向列表。使用 [:2] 您将获得前 2 个对象。
posts = Post.objects.all().order_by("-id")[:2]
推荐阅读
- javascript - 如何按“原始顺序”组装 JavaScript 异步获取结果
- javascript - 过渡:在 svg 元素上变换
- firebase - 带有刷新令牌的 React-Native Firebase 重新认证
- python - Python中的字符串和一位数字字符串数组之间有什么区别吗?
- unit-testing - 如何从 pytest_runtest_makereport 挂钩中识别 xfail 测试?
- netlogo - 如何从 NetLogo 中的行为空间中提取变量
- scala - 如何在Scala中创建一个总和为最大值的半同质整数的迭代?
- node.js - Node.js 服务器同时处理多个请求
- esp32 - ESP32 ULP 协处理器不会及时唤醒
- python-sphinx - 使用 genindex 是否可以有多个自动生成的索引,这些索引的范围是单独的章节?