【Python百日进阶-Web开发-Peewee】Day267 - Peewee API文档 - 查询生成器(三)

11.2.19 class NodeList

class NodeList(nodes[, glue=' '[, parens=False]])

参数:

  • nodes (列表)——零个或多个节点。
  • glue ( str ) – 转换为 SQL 时如何连接节点。
  • parens ( bool ) – 是否将生成的 SQL 包装在括号中。
    表示节点列表、多部分子句、参数列表等。
CommaNodeList(nodes)

参数: 节点( list ) – 零个或多个节点。
回报: 一种NodeList
表示以逗号连接的节点列表。

EnclosedNodeList(nodes)

参数: 节点( list ) – 零个或多个节点。
回报: 一种NodeList
表示由逗号连接并用括号括起来的节点列表。

11.2.20 class DQ

class DQ(**query)
参数: 询问– 使用 Django 样式查找的任意过滤器表达式。
表示适合与Model.filter()orModelSelect.filter()方法一起使用的可组合 Django 样式的过滤器表达式。

11.2.21 class Tuple(*args)

表示一个 SQL行值。大多数数据库都支持行值。

11.2.22 class OnConflict

class OnConflict([action=None[, update=None[, preserve=None[, where=None[, conflict_target=None[, conflict_where=None[, conflict_constraint=None]]]]]]])

参数:

  • action ( str ) – 解决冲突时要采取的行动。
  • update – 字典映射列到新值。
  • preserve - 列的列表,其值应从原始 INSERT 中保留。另请参阅EXCLUDED。
  • where - 限制冲突解决的表达式。
  • conflict_target – 构成约束的列。
  • conflict_where – 如果约束目标是部分索引(带有 WHERE 子句的索引),则需要匹配约束目标的表达式。
  • conflict_constraint ( str ) – 用于解决冲突的约束名称。目前只有 Postgres 支持。
    表示数据修改查询的冲突解决子句。

根据所使用的数据库驱动程序,可能需要一个或多个上述参数。

preserve(*columns)

参数: 列– 应保留其值的列。

update([_data=None[, **kwargs]])

参数:

  • _data ( dict ) – 字典映射列到新值。
  • kwargs – 将列名映射到新值的字典。
    该update()方法支持使用列到值的字典或表示相同的关键字参数调用。

where(*expressions)

参数: 表达式– 限制冲突解决条款作用的表达式。

conflict_target(*constraints)

参数: 约束– 用作冲突解决目标的列。

conflict_where(*expressions)

参数: 表达式– 匹配冲突目标索引的表达式,如果冲突目标是部分索引。

conflict_constraint(constraint)

参数: 约束( str ) – 用作冲突解决目标的约束名称。目前只有 Postgres 支持。

11.2.23 class EXCLUDED

class EXCLUDED

公开与 INSERT … ON CONFLICT 一起使用的 EXCLUDED 命名空间的帮助器对象,以引用冲突数据中的值。这是一个“魔法”助手,因此可以通过访问其上与特定列对应的属性来使用它。

Example:

class KV(Model):
    key = CharField(unique=True)
    value = IntegerField()

# Create one row.
KV.create(key='k1', value=1)

# Demonstrate usage of EXCLUDED.
# Here we will attempt to insert a new value for a given key. If that
# key already exists, then we will update its value with the *sum* of its
# original value and the value we attempted to insert -- provided that
# the new value is larger than the original value.
query = (KV.insert(key='k1', value=10)
         .on_conflict(conflict_target=[KV.key],
                      update={KV.value: KV.value + EXCLUDED.value},
                      where=(EXCLUDED.value > KV.value)))

# Executing the above query will result in the following data being
# present in the "kv" table:
# (key='k1', value=11)
query.execute()

# If we attempted to execute the query *again*, then nothing would be
# updated, as the new value (10) is now less than the value in the
# original row (11).

11.2.24 class BaseQuery

class BaseQuery

派生所有其他查询类的父类。虽然您不会在代码中直接处理 BaseQuery,但它实现了一些在所有查询类型中通用的方法。

default_row_type = ROW.DICT

bind([database=None])

参数: database (Database) – 执行查询的数据库。
将查询绑定到给定的数据库以执行。

dicts([as_dict=True])

参数: as_dict (bool) – 指定是否将行作为字典返回。
将行作为字典返回。

tuples([as_tuples=True])

参数: as_tuple (bool) – 指定是否将行作为元组返回。
将行作为元组返回。

namedtuples([as_namedtuple=True])

参数: as_namedtuple (bool) – 指定是否将行作为命名元组返回。
将行作为命名元组返回。

objects([constructor=None])

参数:constructor – 接受行字典并返回任意对象的函数。
使用给定的构造函数将行作为任意对象返回。

sql()

返回:由查询的 SQL 和参数组成的 2 元组。

execute(database)

参数: database (Database) – 执行查询的数据库。如果查询以前绑定到数据库,则不需要。
执行查询并返回结果(取决于正在执行的查询类型)。例如,选择查询返回结果将是查询结果的迭代器。

iterator([database=None])
参数: database (Database) – 执行查询的数据库。如果查询以前绑定到数据库,则不需要。
执行查询并返回结果集的迭代器。对于大型结果集,此方法更可取,因为在迭代期间行不会缓存在内存中。

笔记
因为行没有被缓存,所以查询只能迭代一次。由于游标已被消耗,后续迭代将返回空结果集。

例子:

query = StatTbl.select().order_by(StatTbl.timestamp).tuples()
for row in query.iterator(db):
process_row(row)

iter ()
执行查询并返回结果集的迭代器。

与 iterator() 不同,此方法将导致缓存行以允许有效的迭代、索引和切片。

getitem (value)
参数: value – 整数索引或切片。
从结果集中检索一行或一系列行。

len ()
返回结果集中的行数。

警告
这不会发出 COUNT() 查询。相反,结果集会像在正常迭代期间那样加载,并且长度由结果集的大小确定。

11.2.25 class RawQuery

class RawQuery([sql=None[, params=None[, **kwargs]]])

参数:

  • sql (str) – SQL 查询。
  • params (tuple) – 参数(可选)。
    通过直接指定要执行的 SQL 创建查询。

11.2.26 class SelectQuery

class SelectQuery

选择实现运算符重载以创建复合查询的查询助手类。

cte(name[, recursive=False[, columns=None]])

参数:

  • name ( str ) – 公用表表达式的别名。
  • recursive ( bool ) – 这将是递归 CTE 吗?
  • columns ( list ) – 列名列表(作为字符串)。
    指示查询将用作公用表表达式。例如,如果我们正在建模类别树并使用父链接外键,我们可以使用递归 CTE 检索所有类别及其绝对深度:
class Category(Model):
    name = TextField()
    parent = ForeignKeyField('self', backref='children', null=True)

# The base case of our recursive CTE will be categories that are at
# the root level -- in other words, categories without parents.
roots = (Category
         .select(Category.name, Value(0).alias('level'))
         .where(Category.parent.is_null())
         .cte(name='roots', recursive=True))

# The recursive term will select the category name and increment
# the depth, joining on the base term so that the recursive term
# consists of all children of the base category.
RTerm = Category.alias()
recursive = (RTerm
             .select(RTerm.name, (roots.c.level + 1).alias('level'))
             .join(roots, on=(RTerm.parent == roots.c.id)))

# Express <base term> UNION ALL <recursive term>.
cte = roots.union_all(recursive)

# Select name and level from the recursive CTE.
query = (cte
         .select_from(cte.c.name, cte.c.level)
         .order_by(cte.c.name))

for category in query:
    print(category.name, category.level)

有关 CTE 的更多示例,请参阅公用表表达式。

select_from(*columns)

参数: 列– 从内部查询中选择一列或多列。
回报: 包装调用查询的新查询。
创建一个包装当前(调用)查询的新查询。例如,假设您有一个简单的UNION查询,并且需要在联合结果集上应用聚合。为此,您需要编写如下内容:

SELECT "u"."owner", COUNT("u"."id") AS "ct"
FROM (
    SELECT "id", "owner", ... FROM "cars"
    UNION
    SELECT "id", "owner", ... FROM "motorcycles"
    UNION
    SELECT "id", "owner", ... FROM "boats") AS "u"
GROUP BY "u"."owner"

该select_from()方法旨在简化构建此类查询。

示例 peewee 代码:

class Car(Model):
    owner = ForeignKeyField(Owner, backref='cars')
    # ... car-specific fields, etc ...

class Motorcycle(Model):
    owner = ForeignKeyField(Owner, backref='motorcycles')
    # ... motorcycle-specific fields, etc ...

class Boat(Model):
    owner = ForeignKeyField(Owner, backref='boats')
    # ... boat-specific fields, etc ...

cars = Car.select(Car.owner)
motorcycles = Motorcycle.select(Motorcycle.owner)
boats = Boat.select(Boat.owner)

union = cars | motorcycles | boats

query = (union
         .select_from(union.c.owner, fn.COUNT(union.c.id))
         .group_by(union.c.owner))

union_all(dest)

使用 .创建一个 UNION ALL 查询dest。

add(dest)

使用 .创建一个 UNION ALL 查询dest。

union(dest)

使用 . 创建一个 UNION 查询dest。

or(dest)

使用 . 创建一个 UNION 查询dest。

intersect(dest)

用 . 创建一个 INTERSECT 查询dest。

and(dest)

用 . 创建一个 INTERSECT 查询dest。

except_(dest)

使用 . 创建一个 EXCEPT 查询dest。请注意,方法名称后面有一个“_”字符,因为except它是 Python 保留字。

sub(dest)

使用 . 创建一个 EXCEPT 查询dest。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

岳涛@心馨电脑

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值