日期:2014-05-16  浏览次数:20661 次

peewee 一个轻量级的ORM (三)


现在该讲讲怎么用peewee查询了

其实peewee实现的这个ORM没有什么特殊的,和其他的ORM在查询表现上差不多。如果我们已经用过其他的ORM就会发现peewee很易于掌握。

table.select(),这就是select * from 。。。。

举个例子。查询用户的is_staff=Tree,他的blog是LIVE状态的记录。

>>> Blog.select().where(status=LIVE).join(User).where(is_staff=True)

注意:这里

join() 两个model,必须是用 ForeignKeyField 连接的.

还有另外一招

>>> Blog.select().where(
...     status=LIVE,
...     user__in=User.select().where(is_staff=True)
... )

而这种没有直接明确的使用JOIN,他用的是where这个子查询

# using subqueries
SELECT * FROM blog
WHERE (
    status = ? AND
    user_id IN (
        SELECT t1.id FROM user AS t1 WHERE t1.is_staff = ?
    )
)

如果用了JOIN,

# using joins
SELECT t1.* FROM blog AS t1
INNER JOIN user AS t2
    ON t1.user_id = t2.id
WHERE
    t1.status = ? AND
    t2.is_staff = ?

查询的时候用到的一些运算符。

==:
x = y
<:
x < y
<=:
x <= y
>:
x > y
>=:
x >= y
!=:
x != y
*:
检查是否包含字串(大小写敏感)
**:
不敏感的检查是否包含字串
^:
大小写不敏感的检查字符串前缀
>>:
x IS (NOT) NULL, depending on if y is True or False
<<:
相当于IN,这里y是一个list或者 SelectQuery

django中

__between:
也就是between,这里y是一个tuple或者list

汇总记录

假如你希望返回blog的记录并且还要附上他在Entry上的记录数。

query = Blog.select().annotate(Entry)

这相当于

query = Blog.select({
    Blog: ['*'],
    Entry: [Count('id')],
}).group_by(Blog).join(Entry)

这样在就除了blog的全部字段信息会返回之外,还加上了在Entry上count的。这两个model在FK非空时连接默认是inner join,也就是如果某个blog没有entries就不会出现在返回记录中了。作为补救,我们要显示设置join的类型。

query = Blog.select().join(Entry, 'left outer').annotate(Entry)

You can also specify a custom aggregator:

query = Blog.select().annotate(Entry, peewee.Max('pub_date', 'max_pub_date'))

但是如果你仅仅想展示一个纯属字信息,比如count,MAX等,那就用