【问题标题】:Access peewee's Meta subclass in Model's outer class method在Model的outer class方法中访问peewee的Meta子类
【发布时间】:2018-12-07 20:58:38
【问题描述】:

我正在尝试将 peewee 模型和类包装到其他接口中,并且我想将模型动态分配给数据库。我为此使用 peewee.Proxy 类,但我不想使用全局变量来使该代理的初始化可用。我想为更改基本模型的 Meta(内部)类创建类方法,但出现以下错误:

AttributeError: type object 'BaseModel' has no attribute 'Meta'

我拥有的代码:

import peewee as pw
class BaseModel(pw.Model):
    class Meta:
        database = pw.Proxy()

    @classmethod
    def configure_proxy(cls, database: pw.Database):
        cls.Meta.database.initialize(database)

当然我可以通过调用 BaseModel.Meta.database 来访问这个变量,但在我看来它不太直观。

你有什么建议吗?

【问题讨论】:

    标签: python python-3.x peewee


    【解决方案1】:

    Peewee 将内部的“Meta”类转换为在类构建后可在“ModelClass._meta”访问的对象:

    将“.Meta”更改为“._meta”:

    class BaseModel(pw.Model):
        class Meta:
            database = pw.Proxy()
    
        @classmethod
        def configure_proxy(cls, database: pw.Database):
            cls._meta.database.initialize(database)
    

    【讨论】:

      【解决方案2】:

      我不知道你为什么会遇到这个问题,我很想知道完整的答案。

      问题在于名称Meta。我猜pw.Model 中定义了这个名字的东西,但我还没有经历过。

      也就是说,这(例如)有效:

      import peewee as pw
      class BaseModel(pw.Model):
          class MyMeta:
              database = pw.Proxy()
      
          @classmethod
          def configure_proxy(cls, database: pw.Database):
              cls.MyMeta.database.initialize(database)
      

      【讨论】:

      猜你喜欢
      • 2015-11-28
      • 1970-01-01
      • 1970-01-01
      • 2021-10-18
      • 2012-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多