sinθ
sinθ

Reputation: 11493

Django: How to limit number of objects returned from a model

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

Answers (2)

Jhanvi Patel
Jhanvi Patel

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

santiagobasulto
santiagobasulto

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

Related Questions