I have a list of news headlines in the database with the following fields: ID, Title, Date. I want to get the last ten (or get them all if there are less than ten).
Sort of:
news = News.objects.order_by("date").first(10)
This is what you need to do:
news = News.objects.order_by("-date")[:10]
There are some interesting things here.
First, to get the latest news, you need a Descending order. (Thats part of "-date") [0]
The second part is the LIMITATION of the result set [1]. This has the same interface as Python Slicing lists [2], but these 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
Source: https://habr.com/ru/post/1446521/More articles:Does file_get_contents () function block? - phpSocket does not work in Python - pythonHow can I have multiple threads in C working on the same loop for a two-dimensional array? - cWhy is it possible to use cross-domain scripts for local files on a mobile device? - javascriptSQL: How to get AVG (MIN (number))? - sqlMongoDB crashes with one ill-named field, what's so special about that? - javaHow to change the default thousands separator of my locale? - c ++Parsing strings with a schema - parsingT SQL - null variable - tsqlPHP Beginner OOP Object Creation - phpAll Articles