Reputation: 11493
I have a list of "news" headlines in a database with the following fields: ID, Title, Date. I want to get the ten latest ones (or retrieve all of them if there are less than ten).
Something like:
news = News.objects.order_by("date").first(10)
Upvotes: 25
Views: 36662
Reputation: 239
My solution
Object returned is actually a list. With using python list indexing we can get any number of objects. Example added below.
'productobj = product_master.objects.all()[0:20]`
Upvotes: 1
Reputation: 11686
This is what you need to do:
news = News.objects.order_by("-date")[:10]
There are a couple of interesting things going on here.
First, to get the lastest news, you need Descending order. (Thats the "-date" part) [0]
The second part is LIMITing the resultset[1]. This shares the same interface as Python lists Slicing[2], but those are different things. Please read them carefully.
[0] https://docs.djangoproject.com/en/dev/ref/models/querysets/#order-by
[1] https://docs.djangoproject.com/en/dev/topics/db/queries/#limiting-querysets
[2] http://docs.python.org/2/tutorial/introduction.html
Upvotes: 50