views:

114

answers:

2

Hello, I am trying to retrieve the latest 5 posts (by post time) In the views.py, if I try blog_post_list = blogPosts.objects.all()[:5] It retreives the first 5 elements of the blogPosts objects, how can I reverse this to retreive the latest ones?

Cheers

+6  A: 
blog_post_list = blogPosts.objects.all().reverse()[:5]
# OR
blog_post_list = blogPosts.objects.all().order_by('-DEFAULT_ORDER_KEY')[:5]

I prefer the first.

Nick Presta
the first one doesn't seem to work for me.And for the second one I get this error:" Caught an exception while rendering: Cannot resolve keyword 'DEFAULT_ORDER_KEY' into field. Choices are: id, postInput, pub_date "
DEFAULT_ORDER_KEY is your order key. You can sort by id, etc. For a blog application, you may want to order by last posted date, in which case the code would be: blogPosts.objects.all().order_by('last_posted')
Nick Presta
+3  A: 

Based on Nick Presta's answer and your comment, try:

blog_post_list = blogPosts.objects.all().order_by('-pub_date')[:5]
Alexander Ljungberg