This article mainly introduces the data chain query in the Django framework and the method for limiting the returned data. Django is the most famous popular framework in the Python framework. For more information, see
Chain query
We usually need to filter and sort queries at the same time. Therefore, you can simply write this form of "chain:
>>> Publisher.objects.filter(country="U.S.A.").order_by("-name")[
,
]
You should have guessed it. converting to an SQL query is a combination of WHERE and ORDER:
SELECT id, name, address, city, state_province, country, websiteFROM books_publisherWHERE country = 'U.S.A'ORDER BY name DESC;
Restrict returned data
Another common requirement is to retrieve a fixed number of records. Imagine that you have thousands of publishers in your database, but you just want to display the first one. You can use the standard Python list cropping statement:
>>> Publisher.objects.order_by('name')[0]
This is equivalent:
SELECT id, name, address, city, state_province, country, websiteFROM books_publisherORDER BY nameLIMIT 1;
Similarly, you can use the range-slicing syntax of Python to retrieve a specific subset of data:
>>> Publisher.objects.order_by('name')[0:2]
In this example, two objects are returned, which is equivalent to the following SQL statement:
SELECT id, name, address, city, state_province, country, websiteFROM books_publisherORDER BY nameOFFSET 0 LIMIT 2;
Note that Python's negative slicing is not supported ):
>>> Publisher.objects.order_by('name')[-1]Traceback (most recent call last): ...AssertionError: Negative indexing is not supported.
Although negative indexes are not supported, we can use other methods. For example, slightly modify the order_by () statement to implement the following:
>>> Publisher.objects.order_by('-name')[0]