Search code examples
pythonpython-3.xpeewee

Access peewee's Meta subclass in Model's outer class method


I'm trying to wrap peewee models and classes into other interface and i want to dynamically assign model to database. I'm using peewee.Proxy class for this, but i don't want to use global variable for making initialization of this proxy available. I wanted to make class method for changing Meta (inner) class of base model, but i get following error:

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

Code that i have:

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)

Of course i could access this variable by calling BaseModel.Meta.database but it is less intuitive in my opinion.

Have you got any suggestions?


Solution

  • Peewee transforms the inner "Meta" class into an object accessible at "ModelClass._meta" after the class is constructed:

    Change ".Meta" to "._meta":

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