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)
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With