Reverse comments list in descending order to get the last n (2) objects in django template

Viewed 64

I've searched a lot and couldn't find anything to reverse the comment's list in descending order so that I can get the last two comments of each post in the template.

Here is my model:

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)

views.py:

posts = Post.objects.all().order_by("date_posted").reverse()
return render(request, "cs50gram/explore.html", {"posts": posts})

template.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 %}

The problem here is that it slices first and then reverse..

What have I tried? How to reverse a for loop in a Django template and then slice the result

Using the solution presented in the answer, it didn't work for some reason. This is exactly how I tried it in my code.

{% 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 %}

The output is that it only slice it without reversing.

Any help in reversing the comment's list in descending order and getting the last n (2) comments of each post is appreciated.


1 Answers

for reverse order just add - sign to order_by value:

posts = Post.objects.order_by("-date_posted")
Related