按降序反转列表以获取django模板中的最后一个对象
我搜索了很多次,没有找到任何东西可以按降序颠倒列表,这样我就可以得到模板中每个帖子的最后两条评论 这是我的模型:按降序反转列表以获取django模板中的最后一个对象,django,django-templates,Django,Django Templates,我搜索了很多次,没有找到任何东西可以按降序颠倒列表,这样我就可以得到模板中每个帖子的最后两条评论 这是我的模型: class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') commented_by = models.ForeignKey(User, on_delete=models.CASCADE) comme
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})
{% 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 %}
template.html:
posts = Post.objects.all().order_by("date_posted").reverse()
return render(request, "cs50gram/explore.html", {"posts": posts})
{% 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 %}
{%for posts in posts%}
{%用于post.comments.all中的注释| slice::2“reversed%}
{{comment.commented_by}}
{{comment.comment}}
{%endfor%}
{%endfor%}
这里的问题是,它先切片,然后反转
我试过什么?
使用答案中给出的解决方案,由于某种原因它不起作用。这正是我在代码中尝试的方式
{% 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 %}
{%for posts in posts%}
{%用于post.comments.all.reverse中的注释|切片::2“%}
{{comment.commented_by}}
{{comment.comment}}
{%endfor%}
{%endfor%}
结果是,它只对其进行切片,而不进行反转
如果您能帮助我们按降序排列列表,并获得每篇文章的最后n(2)条评论,我们将不胜感激
您可以使用order_by('-id')获取反向列表。使用[:2]您将获得前2个对象
posts = Post.objects.all().order_by("-id")[:2]
这是行不通的,因为我希望显示所有帖子,但只显示每个帖子的最后两条评论。