Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

list.reverse() doesn't work properly in Django

I am on my first project with the Django framework, and I decided to create a blog, since it is easy to find stuff about it online. I, then, found out about the Paginator module, and decided to use it. The problem is, whenever I add a post it goes to the end of the Database, so I have a blog that, so far, displays old posts first.

Because of that, I decided to use .reverse(), like this:

def index(request):
    posts = Post.objects.all()
    posts.reverse()
    paginator = Paginator(posts, 2)

    try:
        page = int(request.GET.get("page", "1"))
    except ValueError:
        page = 1

    try:
        posts = paginator.page(page)
    except (InvalidPage, EmptyPage):
        posts = paginator.page(paginator.num_pages)

    return render_to_response('index.html', {
                                             'Posts': posts,
                                             'Sideposts': Sidepost.objects.all(),
                                             })

The only problem is, this doesn't work, at least not with Paginator. When I stop using Paginator it works, but otherwise it doesn't.

I think this is a really weird behaviour, and I had a look around but couldn't find anything that helped me with this problem. Am I doing anything wrong?

like image 214
AugustoQ Avatar asked Dec 25 '22 16:12

AugustoQ


2 Answers

Let the database do the ordering:

posts = Post.objects.all().order_by('-id')

Of course, it would be better to use a date field or something.

like image 82
joshua Avatar answered Jan 02 '23 23:01

joshua


First, Post.objects.all() does not return a list object, but queryset object.

And reverse method does not change the queryset itself, but returns reversed version of queryset.

Convert it to list posts = list(Post.objects.all()) to use reverse method if you want list object.

Maybe following is more preferable:

posts = Post.objects.all().reverse()
like image 21
falsetru Avatar answered Jan 02 '23 23:01

falsetru