Home Backend Development Python Tutorial Python ORM框架SQLAlchemy学习笔记之数据查询实例

Python ORM框架SQLAlchemy学习笔记之数据查询实例

Jun 16, 2016 am 08:43 AM
python sqlalchemy

前期我们做了充足的准备工作,现在该是关键内容之一查询了,当然前面的文章中或多或少的穿插了些有关查询的东西,比如一个查询(Query)对象就是通过Session会话的query()方法获取的,需要注意的是这个方法的参数数目是可变的,也就是说我们可以传入任意多的参数数目,参数的类型可以是任意的类组合或者是类的名称,接下来我们的例子就说明了这一点,我们让Query对象加载了User实例。

复制代码 代码如下:

>>> for instance in session.query(User).order_by(User.id):
...     print instance.name, instance.fullname
SELECT users.id AS users_id,
        users.name AS users_name,
        users.fullname AS users_fullname,
        users.password AS users_password
FROM users ORDER BY users.id
()

ed Ed Jones
wendy Wendy Williams
mary Mary Contrary
fred Fred Flinstone

当然通过这个例子我们得到Query对象返回的是一组可迭代的User实例表,然后我们通过for in语句访问,比如说这里可以依次输出“用户名”instance.name和“用户全名”instance.fullname。大家可能还注意到后面有个.order_by(User.id),这个和SQL语句一样的,指示结果集按User.id所映射的表列进行排序。

假设我们仅仅只需要“用户名”和“用户全名”,对于对象实例的其他属性不感兴趣的话,也可以直接查询它们(类的属性名称),当然这里的前提是这个类必须是ORM映射的,无论何时,任意数目的类实体或者基于列的实体均可以作为query()方法的参数,当然最终Query对象会返回元组类型。

复制代码 代码如下:

>>> for name, fullname in session.query(User.name, User.fullname):
...     print name, fullname
SELECT users.name AS users_name,
        users.fullname AS users_fullname
FROM users
()

ed Ed Jones
wendy Wendy Williams
mary Mary Contrary
fred Fred Flinstone
返回的元组类型也可以被看作是普通的Python对象,属性名称归属性名称,类型名称归类型名称,比如下面的例子:
复制代码 代码如下:

>>> for row in session.query(User, User.name).all():
...    print row.User, row.name
SELECT users.id AS users_id,
        users.name AS users_name,
        users.fullname AS users_fullname,
        users.password AS users_password
FROM users
()

ed
wendy
mary
fred
当然你也可以搞点个性化,比如通过label()方法改变单独的列表达式名称,当然这个方法只有在映射到实体表的列元素对象(ColumnElement-derived)中存在(比如 User.name):
复制代码 代码如下:

>>> for row in session.query(User.name.label('name_label')).all():
...    print(row.name_label)
SELECT users.name AS name_label
FROM users
()

ed
wendy
mary
fred
之前我们看到查询对象实例必须用到实体类的全名(User),假设我们要多次使用这个实体类名作为查询对象(比如表连接操作)query()的参数,则我们可以给它取个“别名”,然后就可以通过别名来传入参数:
复制代码 代码如下:

>>> from sqlalchemy.orm import aliased
>>> user_alias = aliased(User, name='user_alias')

>>> for row in session.query(user_alias, user_alias.name).all():
...    print row.user_alias
SELECT user_alias.id AS user_alias_id,
        user_alias.name AS user_alias_name,
        user_alias.fullname AS user_alias_fullname,
        user_alias.password AS user_alias_password
FROM users AS user_alias
()





学过MySQL等这类数据库的同学可能知道LIMIT和OFFSET这两个SQL操作,这个能够很方便的帮助我们控制记录的数目和位置,常常被用于数据分页操作,当然这类操作SQLAlchemy的Query对象已经帮我们想好了,而且很简单的可以通过Python数组分片来实现,这个操作常常和ORDER BY一起使用:
复制代码 代码如下:

>>> for u in session.query(User).order_by(User.id)[1:3]:
...    print u
SELECT users.id AS users_id,
        users.name AS users_name,
        users.fullname AS users_fullname,
        users.password AS users_password
FROM users ORDER BY users.id
LIMIT ? OFFSET ?
(2, 1)



假如我们需要筛选过滤特定结果,则可以使用filter_by()方法,这个方法使用关键词参数:
复制代码 代码如下:

>>> for name, in session.query(User.name).\
...             filter_by(fullname='Ed Jones'):
...    print name
SELECT users.name AS users_name FROM users
WHERE users.fullname = ?
('Ed Jones',)

ed
或者使用filter()同样能达到目的,不过需要注意的是其使用了更加灵活的类似SQL语句的表达式结构,这意味着你可以在其内部使用Python自身的操作符,比如比较操作:
复制代码 代码如下:

>>> for name, in session.query(User.name).\
...             filter(User.fullname=='Ed Jones'):
...    print name
SELECT users.name AS users_name FROM users
WHERE users.fullname = ?
('Ed Jones',)

ed
注意这里的User.fullname=='Ed Jones',比较操作与Ed Jones相等的才筛选。

当然强大的Query对象有个很有用的特性,那就是它是可以串联的,意味着Query对象的每一步操作将会返回一个Query对象,你可以将相同的方法串联到一起形成表达式结构,假如说我们要查询用户名为”ed”并且全名为”Ed Jones”的用户,你可以直接串联调用filter()两次,表示SQL语句里的AND连接:

复制代码 代码如下:

>>> for user in session.query(User).\
...          filter(User.name=='ed').\
...          filter(User.fullname=='Ed Jones'):
...    print user
SELECT users.id AS users_id,
        users.name AS users_name,
        users.fullname AS users_fullname,
        users.password AS users_password
FROM users
WHERE users.name = ? AND users.fullname = ?
('ed', 'Ed Jones')


下面列举一些使用filter()常见的筛选过滤操作:

1. 相等

复制代码 代码如下:
query.filter(User.name == 'ed')
2. 不等
复制代码 代码如下:
query.filter(User.name != 'ed')
3. LIKE
复制代码 代码如下:
query.filter(User.name.like('%ed%'))
4. IN
复制代码 代码如下:

query.filter(User.name.in_(['ed', 'wendy', 'jack']))

# works with query objects too:

query.filter(User.name.in_(session.query(User.name).filter(User.name.like('%ed%'))))
5. NOT IN
复制代码 代码如下:
query.filter(~User.name.in_(['ed', 'wendy', 'jack']))
6. IS NULL
复制代码 代码如下:
filter(User.name == None)
7. IS NOT NULL
复制代码 代码如下:
filter(User.name != None)
8. AND
复制代码 代码如下:

from sqlalchemy import and_
filter(and_(User.name == 'ed', User.fullname == 'Ed Jones'))

# or call filter()/filter_by() multiple times
filter(User.name == 'ed').filter(User.fullname == 'Ed Jones')
9. OR
复制代码 代码如下:

from sqlalchemy import or_
filter(or_(User.name == 'ed', User.name == 'wendy'))
10. 匹配
复制代码 代码如下:

query.filter(User.name.match('wendy'))
match()参数内容由数据库后台指定。(注:原文是“The contents of the match parameter are database backend specific.”,不太明白这个操作的意思)

好了,今天就介绍这么多,基本上都是蹩脚的翻译,希望对大家能够帮助

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1269
29
C# Tutorial
1249
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

See all articles