Home > Backend Development > Python Tutorial > Django框架中数据的连锁查询和限制返回数据的方法

Django框架中数据的连锁查询和限制返回数据的方法

WBOY
Release: 2016-06-06 11:14:01
Original
1471 people have browsed it

连锁查询

通常我们需要同时进行过滤和排序查询的操作。 因此,你可以简单地写成这种“链式”的形式:

>>> Publisher.objects.filter(country="U.S.A.").order_by("-name")
[<Publisher: O'Reilly>, <Publisher: Apress>]

Copy after login

你应该没猜错,转换成SQL查询就是 WHERE 和 ORDER BY 的组合:

SELECT id, name, address, city, state_province, country, website
FROM books_publisher
WHERE country = 'U.S.A'
ORDER BY name DESC;

Copy after login

限制返回的数据

另一个常用的需求就是取出固定数目的记录。 想象一下你有成千上万的出版商在你的数据库里, 但是你只想显示第一个。 你可以使用标准的Python列表裁剪语句:

>>> Publisher.objects.order_by('name')[0]
<Publisher: Apress>

Copy after login

这相当于:

SELECT id, name, address, city, state_province, country, website
FROM books_publisher
ORDER BY name
LIMIT 1;

Copy after login

类似的,你可以用Python的range-slicing语法来取出数据的特定子集:

>>> Publisher.objects.order_by('name')[0:2]

Copy after login

这个例子返回两个对象,等同于以下的SQL语句:

SELECT id, name, address, city, state_province, country, website
FROM books_publisher
ORDER BY name
OFFSET 0 LIMIT 2;

Copy after login

注意,不支持Python的负索引(negative slicing):

>>> Publisher.objects.order_by('name')[-1]
Traceback (most recent call last):
 ...
AssertionError: Negative indexing is not supported.

Copy after login

虽然不支持负索引,但是我们可以使用其他的方法。 比如,稍微修改 order_by() 语句来实现:

>>> Publisher.objects.order_by('-name')[0]

Copy after login


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template