Peewee 动态定义数据库


如果你的数据库计划在运行时变化,请使用 数据库代理 帮助更好地控制你如何初始化它。 DatabaseProxy 对象是一个占位符,借助它可以在运行时选择哪个数据库。

在以下示例中,根据应用程序的配置设置选择适当的数据库。

from peewee import *
db_proxy = DatabaseProxy() # Create a proxy for our db.

class MyUser (Model):
    name=TextField()
    city=TextField(constraints=[SQL("DEFAULT 'Mumbai'")])
    age=IntegerField()
    class Meta:
        database=db_proxy
        db_table='MyUser'

# Based on configuration, use a different database.
if app.config['TESTING']:
    db = SqliteDatabase(':memory:')
elif app.config['DEBUG']:
    db = SqliteDatabase('mydatabase.db')
else:
    db = PostgresqlDatabase(
        'mydatabase', host='localhost', port=5432, user='postgres', password='postgres'
    )

# Configure our proxy to use the db we specified in config.
db_proxy.initialize(db)
db.connect()
db.create_tables([MyUser])

你还可以在运行时将模型关联到任何数据库对象,使用 bind() 在数据库类和模型类中声明的方法。

以下示例在数据库类中使用 bind() 方法。

from peewee import *

class MyUser (Model):
    name=TextField()
    city=TextField(constraints=[SQL("DEFAULT 'Mumbai'")])
    age=IntegerField()

db = MySQLDatabase('mydatabase', host='localhost', port=3306, user='root', password='')
db.connect()
db.bind([MyUser])
db.create_tables([MyUser])

在 Model 类中也定义了相同的 bind() 方法。

from peewee import *

class MyUser (Model):
    name=TextField()
    city=TextField(constraints=[SQL("DEFAULT 'Mumbai'")])
    age=IntegerField()

db = MySQLDatabase('mydatabase', host='localhost', port=3306, user='root', password='')
db.connect()
MyUser.bind(db)
db.create_tables([MyUser])