Home > Backend Development > Python Tutorial > Python的Django框架中的数据过滤功能

Python的Django框架中的数据过滤功能

WBOY
Release: 2016-06-10 15:09:17
Original
1305 people have browsed it

我们很少会一次性从数据库中取出所有的数据;通常都只针对一部分数据进行操作。 在Django API中,我们可以使用`` filter()`` 方法对数据进行过滤:

>>> Publisher.objects.filter(name='Apress')
[<Publisher: Apress>]

Copy after login

filter() 根据关键字参数来转换成 WHERE SQL语句。 前面这个例子 相当于这样:

SELECT id, name, address, city, state_province, country, website
FROM books_publisher
WHERE name = 'Apress';

Copy after login

你可以传递多个参数到 filter() 来缩小选取范围:

>>> Publisher.objects.filter(country="U.S.A.", state_province="CA")
[<Publisher: Apress>]

Copy after login

多个参数会被转换成 AND SQL从句, 因此上面的代码可以转化成这样:

SELECT id, name, address, city, state_province, country, website
FROM books_publisher
WHERE country = 'U.S.A.'
AND state_province = 'CA';

Copy after login

注意,SQL缺省的 = 操作符是精确匹配的, 其他类型的查找也可以使用:

>>> Publisher.objects.filter(name__contains="press")
[<Publisher: Apress>]

Copy after login

在 name 和 contains 之间有双下划线。和Python一样,Django也使用双下划线来表明会进行一些魔术般的操作。这里,contains部分会被Django翻译成LIKE语句:

SELECT id, name, address, city, state_province, country, website
FROM books_publisher
WHERE name LIKE '%press%';

Copy after login

其他的一些查找类型有:icontains(大小写无关的LIKE),startswith和endswith, 还有range(SQLBETWEEN查询)。

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