1. 返回列表和标量(scalar)
前面我们注意到query对象可以返回可迭代的值(iterator value),然后我们可以通过for in来查询。不过query对象的all()、one()以及first()方法将返回非迭代值(non-iterator value),比如说all()返回的是一个列表:
>>> query = session.query(user).\
>>> filter(user.name.like(‘%ed’)).order_by(user.id)
>>> query.all()
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 like ? order by users.id
(‘%ed’,)
[user(‘ed’,’ed jones’, ‘f8s7ccs’), user(‘fred’,’fred flinstone’, ‘blah’)]
first()方法限制并仅作为标量返回结果集的第一条记录:
>>> query.first()
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 like ? order by users.id
limit ? offset ?
(‘%ed’, 1, 0)
one()方法,完整的提取所有的记录行,并且如果没有明确的一条记录行(没有找到这条记录)或者结果中存在多条记录行,将会引发错误异常noresultfound或者multipleresultsfound:
>>> from sqlalchemy.orm.exc import multipleresultsfound
>>> try:
… user = query.one()
… except multipleresultsfound, e:
… print e
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 like ? order by users.id
(‘%ed’,)
multiple rows were found for one()
>>> from sqlalchemy.orm.exc import noresultfound
>>> try:
… user = query.filter(user.id == 99).one()
… except noresultfound, e:
… print e
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 like ? and users.id = ? order by users.id
(‘%ed’, 99)
no row was found for one()
2. 使用原义sql (literal sql)
query对象能够灵活的使用原义sql查询字符串作为查询参数,比如我们之前用过的filter()和order_by()方法:
>>> for user in session.query(user).\
… filter(“id