文章目录
11.4 模式管理器
http://docs.peewee-orm.com/en/latest/peewee/api.html#schema-manager
11.4.1 class SchemaManager
class SchemaManager(model[,database=None[, **context_options]])
参数:
- model(model)——model类。
- database ( Database ) – 如果未指定,则默认为 model._meta.database。
提供用于管理给定model的表和索引的创建和删除的方法。
create_table([safe=True[, **options]])
参数:
- safe ( bool ) – 指定 IF NOT EXISTS 子句。
- options - 任意选项。
对给定model执行 CREATE TABLE 查询。
drop_table([safe=True[, drop_sequences=True[, **options]]])
参数:
- safe ( bool ) – 指定 IF EXISTS 子句。
- drop_sequences ( bool ) – 删除与表上的列关联的任何序列(仅限 postgres)。
- options - 任意选项。
对给定model执行 DROP TABLE 查询。
truncate_table([restart_identity=False[,cascade=False]])
参数:
- restart_identity ( bool ) – 重新启动 id 序列(仅限 postgres)。
- cascade ( bool ) – 也截断相关表(仅限 postgres)。
对给定model执行 TRUNCATE TABLE。如果数据库是不支持 TRUNCATE 的 Sqlite,则将执行等效的 DELETE 查询。
create_indexes([safe=True])
参数: safe( bool ) – 指定 IF NOT EXISTS 子句。
为model定义的索引执行 CREATE INDEX 查询。
drop_indexes([safe=True])
参数: safe( bool ) – 指定 IF EXISTS 子句。
为model定义的索引执行 DROP INDEX 查询。
create_sequence(field)
参数: field( Field ) – 指定序列的字段实例。
为给定的创建序列Field。
drop_sequence(field)
参数: field( Field ) – 指定序列的字段实例。
给定的删除序列Field。
create_foreign_key(field)
参数: field( ForeignKeyField ) – 要添加的外键字段约束。
为给定字段添加外键约束。在大多数情况下,此方法不是必需的,因为外键约束是作为表创建的一部分创建的。例外情况是当您使用 . 创建循环外键关系时DeferredForeignKey。在这些情况下,有必要首先创建表,然后为延迟外键添加约束:
class Language(Model):
name = TextField()
selected_snippet = DeferredForeignKey('Snippet')
class Snippet(Model):
code = TextField()
language = ForeignKeyField(Language, backref='snippets')
# Creates both tables but does not create the constraint for the
# Language.selected_snippet foreign key (because of the circular
# dependency).
db.create_tables([Language, Snippet])
# Explicitly create the constraint:
Language._schema.create_foreign_key(Language.selected_snippet)
有关详细信息,请参阅有关循环外键依赖项的文档。
警告
由于 SQLite 对更改现有表的支持有限,因此无法向现有 SQLite 表添加外键约束。
create_all([safe=True[, **table_options]])
参数: safe( bool ) – 是否指定 IF NOT EXISTS。
为model创建序列、索引和表。
drop_all([safe=True[, drop_sequences=True[, **options]]])
参数:
- safe ( bool ) – 是否指定 IF EXISTS。
- drop_sequences ( bool ) – 删除与表上的列关联的任何序列(仅限 postgres)。
- options - 任意选项。
删除model和相关索引的表。
11.5 model 模型
http://docs.peewee-orm.com/en/latest/peewee/api.html#model
11.5.1 class Metadata
class Metadata(model[, database=None[, table_name=None[, indexes=None[, primary_key=None[, constraints=None[, schema=None[, only_save_dirty=False[, depends_on=None[, options=None[, without_rowid=False[, strict_tables=False[, **kwargs]]]]]]]]]]]]])
参数:
- model(model)——model类。
- database( Database ) – 数据库model绑定到。
- table_name ( str ) – 指定model的表名。
- indexes( list ) --ModelIndex对象列表。
- primary_key – model的主键(仅在这是 主键CompositeKey或False没有主键时指定。
- constraints( list ) – 表约束列表。
- schema ( str ) – Schema 表存在于。
- only_save_dirty ( bool ) --save()调用时,只保存已修改的字段。
- options ( dict ) – model的任意选项。
- without_rowid ( bool ) – 指定 WITHOUT ROWID(仅限 sqlite)。
- strict_tables ( bool ) – 指定 STRICT(仅限 sqlite,需要 3.37+)。
- kwargs – 任意设置属性和值。
存储Model元数据。
这个类不应该直接实例化,而是使用Model类的内部Meta类的属性来实例化。元数据属性随后可在Model._meta
.
table
返回对基础Table对象的引用。
model_graph([refs=True[, backrefs=True[,depth_first=True]]])
参数:
- refs ( bool ) – 遵循外键引用。
- backrefs ( bool ) – 遵循外键反向引用。
- depth_first ( bool ) – 进行深度优先搜索(False对于广度优先)。
遍历model图并返回一个三元组列表,包括 .(foreign key field, model class, is_backref)
set_database(database)
参数: database( Database ) – 将model绑定到的数据库对象。
将model类绑定到给定的Database实例。
警告
不需要使用此 API。相反,要在运行时更改 Model数据库,请使用以下方法之一:
- Model.bind()
- Model.bind_ctx()(绑定上下文管理器的范围)。
- Database.bind()
- Database.bind_ctx()
set_table_name(table_name)
参数: table_name( str ) – 要将model绑定到的表名。
在运行时将model类绑定到给定的表名。
11.5.2 class SubclassAwareMetadata
class SubclassAwareMetadata
跟踪子类的元数据子Model类。
map_models( fn )
将函数应用于所有子类。
11.5.3 class ModelAlias
class ModelAlias(model[, alias=None])
参数:
model (Model) – 要引用的模型类。
alias (str) - (可选)别名的名称。
在查询中提供对模型的单独引用。
11.5.4 class ModelSelect
class ModelSelect(model, fields_or_models)
参数:
model (Model) – 要选择的模型类。
fields_or_models – 要选择的字段或模型类的列表。
SELECT 查询的特定于模型的实现。
switch([ctx=None])
参数: ctx – 模型、模型别名、子查询或其他已连接的对象。
切换连接上下文 - 随后对 join() 的调用将被连接到的源。用于针对单个表指定多个连接。
如果未给出 ctx,则将使用查询的模型。
以下示例从推文中选择并加入用户和推文标志:
sq = Tweet.select().join(User).switch(Tweet).join(TweetFlag)
# Equivalent (since Tweet is the query's model)
sq = Tweet.select().join(User).switch().join(TweetFlag)
objects([constructor=None])
参数:constructor – Constructor(默认返回模型实例)将
结果行作为使用给定创建的对象返回构造函数。默认行为是创建模型实例。
笔记
当从多个源/模型中选择字段数据时,可以使用此方法使所有数据作为被查询模型上的属性可用(而不是构建连接模型实例的图)。对于非常复杂的查询,这可能会对性能产生积极影响,尤其是迭代大型结果集。
同样,您可以使用 dicts()、tuples() 或 namedtuples() 来获得更高的性能。
join(dest[, join_type=‘INNER’[, on=None[, src=None[, attr=None]]]])
参数:
dest – 模型、模型别名、选择查询或其他要加入的对象。
join_type (str) – 连接类型,默认为 INNER。
on – 加入谓词或 ForeignKeyField 加入。
src – 明确指定连接的来源。如果未指定,则将使用当前连接上下文。
attr (str) – 从连接模型投影列时使用的属性。
加入另一个类似表格的对象。
连接类型可以是以下之一:
- JOIN.INNER
- JOIN.LEFT_OUTER
- JOIN.RIGHT_OUTER
- JOIN.FULL
- JOIN.FULL_OUTER
- JOIN.CROSS
选择推文并加入用户以限制仅由“管理员”用户发布的推文的示例:
sq = Tweet.select().join(User).where(User.is_admin == True)
选择用户并加入特定外键字段的示例。请参阅示例应用程序以了解实际使用情况:
sq = User.select().join(Relationship, on=Relationship.to_user)
有关模型之间的外键、连接和关系的深入讨论,请参阅关系和连接。
join_from(src, dest[, join_type=‘INNER’[, on=None[, attr=None]]])
参数:
src – 连接源。
dest – 要加入的表。
使用与非特定于模型的 join() 相同的参数顺序。通过要求指定连接源来绕过连接上下文。
filter(*args, **kwargs)
参数:
args – 零个或多个 DQ 对象。
kwargs – Django 风格的关键字参数过滤器。
使用 Django 样式的过滤器来表达 WHERE 子句。
prefetch(*subqueries)
参数: subqueries – 模型类列表或要预取的选择查询。
返回:预取选定关系的模型列表。
执行查询,预取给定的附加资源。
另请参见 prefetch() 独立函数。
例子:
# Fetch all Users and prefetch their associated tweets.
query = User.select().prefetch(Tweet)
for user in query:
print(user.username)
for tweet in user.tweets:
print(' *', tweet.content)
注意
由于预取必须重构模型图,因此必须确保选择任何相关模型的外键/主键,以便正确映射相关对象。
prefetch(sq, *subqueries)
参数:
sq – 用作起点的查询。
子查询——一个或多个模型或 ModelSelect 查询急切地获取。
返回:
预取选定关系的模型列表。
急切地获取相关对象,允许在存在一对多关系时高效查询多个表。
例如,高效查询多对一关系很简单:
query = (Tweet
.select(Tweet, User)
.join(User))
for tweet in query:
# Looking up tweet.user.username does not require a query since
# the related user's columns were selected.
print(tweet.user.username, '->', tweet.content)
为了有效地进行反向查询,查询用户及其推文,您可以使用预取:
query = User.select()
for user in prefetch(query, Tweet):
print(user.username)
for tweet in user.tweets: # Does not require additional query.
print(' ', tweet.content)
注意
由于预取必须重构模型图,因此必须确保选择任何相关模型的外键/主键,以便正确映射相关对象。