views:

44

answers:

4

I have a simply class

class BlogPost(models.Model):
title = models.CharField(max_length=150)
...
timestamp = models.DateTimeField()

How do I get the last five items from the database. I tried to do like this:

posts = BlogPost.objects.<any code>

Excuse me for bad English

+3  A: 

You need to invest some time in Reading The Friggin' Manual. Django is one of the best documented open source projects on the planet.

Her's the specific thing you want to read, Limiting QuerySets, but you really need to read the whole page (and a few others) if you are going to do anything meaningful with Django.

Peter Rowell
+1 for the good advice ;) and the link to the solution.
Manoj Govindan
Is there a more streamlined operation? That is why I am taking all the elements and then choose only a small amount.Excuse me for bad English
cristaloleg
A: 

You use the array-slicing syntax to index into your queryset, and you use the reverse() function to reverse the queryset before indexing, e.g., myQuerySet.reverse()[:5]. See the docs for more details.

Hank Gay
What assumptions are you making that reversing the query set will provide the correct ordering?
Joe Holloway
@Joe Holloway He said he wanted the last 5 items. I gave him the general solution for that problem. @awithrow's syntax is obviously more idiomatic for this particular problem.
Hank Gay
A: 
BlogPost.objects.order_by('-timestamp')[:5]
awithrow
A: 

I think that ordering by id it's faster than sorting by any other field.

Teodor Pripoae