peewee - 与 Database() 初始化分开定义模型
peewee - Define models separately from Database() initialization
我需要使用一些 ORM 引擎,例如 peewee,以便在我的 python 应用程序中处理 SQLite 数据库。但是,大多数此类库都提供这样的语法来定义 models.py
:
import peewee
db = peewee.Database('hello.sqlite')
class Person(peewee.Model):
name = peewee.CharField()
class Meta:
database = db
但是,在我的应用程序中,我无法使用这种语法,因为数据库文件名是在导入后由外部代码从模块提供的,该模块导入了我的 models.py
.
如何从知道动态数据库文件名的定义之外初始化模型?理想情况下,models.py
根本不应该包含 "database" 提及,就像普通的 ORM。
也许您正在查看代理功能:
proxy - peewee
database_proxy = Proxy() # Create a proxy for our db.
class BaseModel(Model):
class Meta:
database = database_proxy # Use proxy for our DB.
class User(BaseModel):
username = CharField()
# Based on configuration, use a different database.
if app.config['DEBUG']:
database = SqliteDatabase('local.db')
elif app.config['TESTING']:
database = SqliteDatabase(':memory:')
else:
database = PostgresqlDatabase('mega_production_db')
# Configure our proxy to use the db we specified in config.
database_proxy.initialize(database)
我需要使用一些 ORM 引擎,例如 peewee,以便在我的 python 应用程序中处理 SQLite 数据库。但是,大多数此类库都提供这样的语法来定义 models.py
:
import peewee
db = peewee.Database('hello.sqlite')
class Person(peewee.Model):
name = peewee.CharField()
class Meta:
database = db
但是,在我的应用程序中,我无法使用这种语法,因为数据库文件名是在导入后由外部代码从模块提供的,该模块导入了我的 models.py
.
如何从知道动态数据库文件名的定义之外初始化模型?理想情况下,models.py
根本不应该包含 "database" 提及,就像普通的 ORM。
也许您正在查看代理功能: proxy - peewee
database_proxy = Proxy() # Create a proxy for our db.
class BaseModel(Model):
class Meta:
database = database_proxy # Use proxy for our DB.
class User(BaseModel):
username = CharField()
# Based on configuration, use a different database.
if app.config['DEBUG']:
database = SqliteDatabase('local.db')
elif app.config['TESTING']:
database = SqliteDatabase(':memory:')
else:
database = PostgresqlDatabase('mega_production_db')
# Configure our proxy to use the db we specified in config.
database_proxy.initialize(database)