【问题标题】:peewee multiple database with "Using" decorator带有“使用”装饰器的 peewee 多数据库
【发布时间】:2021-11-02 11:20:12
【问题描述】:

在 peewee documentation 中,它说您可以使用“使用”装饰器来利用多个数据库

master = PostgresqlDatabase('master')
read_replica = PostgresqlDatabase('replica')

class Data(Model):
    value = IntegerField()

    class Meta:
        database = master

with Using(read_replica, [Data]):
    # Query is executed against the read replica.
    Data.get(Data.value == 5)

    # Since we did not specify this model in the list of overrides
    # it will use whatever database it was defined with.
    SomeOtherModel.get(SomeOtherModel.field == 3)

在上面的例子中,你可以通过“Using”装饰器使用多个数据库。

我的问题是如何导入“使用”装饰器?

我找不到任何关于导入 Using 装饰器的代码。

【问题讨论】:

标签: python decorator using peewee multiple-databases


【解决方案1】:

您使用的是 2.x 文档,请尝试使用文档版本来匹配您正在使用的 peewee 版本。从 3.0 开始执行此操作的方法是使用 bind() 和 bind_ctx() 方法:

http://docs.peewee-orm.com/en/latest/peewee/api.html#Database.bind_ctx

master = PostgresqlDatabase('master')
read_replica = PostgresqlDatabase('replica')

class Data(Model):
    value = IntegerField()

    class Meta:
        database = master

with read_replica.bind_ctx([Data]):
    # Query is executed against the read replica.
    Data.get(Data.value == 5)

    # Since we did not specify this model in the list of overrides
    # it will use whatever database it was defined with.
    SomeOtherModel.get(SomeOtherModel.field == 3)

【讨论】:

    猜你喜欢
    • 2014-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-23
    • 2020-09-05
    • 2011-10-23
    • 1970-01-01
    • 2013-02-10
    相关资源
    最近更新 更多