首页 > 解决方案 > 按降序反转列表以获取 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) 条评论的帮助,我们将不胜感激。


标签: djangodjango-templates

解决方案


您可以使用 order_by('-id') 来获取反向列表。使用 [:2] 您将获得前 2 个对象。

posts = Post.objects.all().order_by("-id")[:2]

推荐阅读