Django: how to limit the number of objects returned from a model

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) 
+4
source share
1 answer

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

+14
source

Source: https://habr.com/ru/post/1446521/


All Articles