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

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]`

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

Tags:

Python

Django