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?
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With