Peewee 简明教程
Peewee - PostgreSQL and MySQL Extensions
playhouse.postgres_ext 中定义的帮助程序启用了额外的 PostgreSQL 功能。该模块定义了 PostgresqlExtDatabase 类,并提供了以下额外字段类型,这些类型专门用于声明要映射到 PostgreSQL 数据库表的模型。
Additional PostgreSQL functionality is enabled by helpers which are defined in playhouse.postgres_ext module. This module defines PostgresqlExtDatabase class and provides the following additional field types to be exclusively used for declaration of model to be mapped against PostgreSQL database table.
Features of PostgreSQL Extensions
Peewee 支持的 PostgreSQL 扩展功能如下 −
The features of PostgreSQL Extensions which are supported by Peewee are as follows −
-
ArrayField field type, for storing arrays.
-
HStoreField field type, for storing key/value pairs.
-
IntervalField field type, for storing timedelta objects.
-
JSONField field type, for storing JSON data.
-
BinaryJSONField field type for the jsonb JSON data type.
-
TSVectorField field type, for storing full-text search data.
-
DateTimeTZField field type, a timezone-aware datetime field.
此模块中的其他特定于 Postgres 的功能旨在提供。
Additional Postgres-specific features in this module are meant to provide.
-
hstore support.
-
server-side cursors.
-
full-text search.
Postgres hstore 是一个键值存储,可嵌入到表中作为 HStoreField 类型字段之一。要启用 hstore 支持,请创建具有 register_hstore=True 参数的数据库实例。
Postgres hstore is a key:value store that can be embedded in a table as one of the fields of type HStoreField. To enable hstore support, create database instance with register_hstore=True parameter.
db = PostgresqlExtDatabase('mydatabase', register_hstore=True)
使用一个 HStoreField 定义一个模型。
Define a model with one HStoreField.
class Vehicles(BaseExtModel):
type = CharField()
features = HStoreField()
按如下方式创建一个模型实例 −
Create a model instance as follows −
v=Vechicle.create(type='Car', specs:{'mfg':'Maruti', 'Fuel':'Petrol', 'model':'Alto'})
要访问 hstore 值 −
To access hstore values −
obj=Vehicle.get(Vehicle.id=v.id)
print (obj.features)
MySQL Extensions
由 playhouse.mysql_ext 模块中定义的 MySQLConnectorDatabase 提供 MysqlDatabase 类的备用实现。它使用 Python 的 DB-API 兼容官方 mysql/python connector 。
Alternate implementation of MysqlDatabase class is provided by MySQLConnectorDatabase defined in playhouse.mysql_ext module. It uses Python’s DB-API compatible official mysql/python connector.
from playhouse.mysql_ext import MySQLConnectorDatabase
db = MySQLConnectorDatabase('mydatabase', host='localhost', user='root', password='')