Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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)
like image 274
sinθ Avatar asked Nov 16 '12 18:11

sinθ


People also ask

How do I limit query results in Django?

Use a subset of Python's array-slicing syntax to limit your QuerySet to a certain number of results. This is the equivalent of SQL's LIMIT and OFFSET clauses. Negative indexing (i.e. Entry.objects.all()[-1] ) is not supported.

What does objects all () return in Django?

all() Returns a copy of the current QuerySet (or QuerySet subclass). This can be useful in situations where you might want to pass in either a model manager or a QuerySet and do further filtering on the result. After calling all() on either object, you'll definitely have a QuerySet to work with.

What does .values do in Django?

values() Returns a QuerySet that returns dictionaries, rather than model instances, when used as an iterable. Each of those dictionaries represents an object, with the keys corresponding to the attribute names of model objects.

What is reduce in Django?

reduce is a built-in function similar to the code below: def reduce(func, items): result = items.pop() for item in items: result = func(result, item) return result. Where func is a user defined function. operator.or_ is a python standard library function that wraps the or operator.


1 Answers

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

like image 83
santiagobasulto Avatar answered Oct 06 '22 01:10

santiagobasulto