klen / peewee-aio

Async support for Peewee ORM
44 stars 7 forks source link

Is it possible to create manager object later? #10

Open the-vindicar opened 1 year ago

the-vindicar commented 1 year ago

In the example you create a manager object first, and give it a database URL before defining your models. However, peewee allows you to create a Database object without actually associating it to a database, and connect it afterwards. Is it possible to create a manager without specifying the database, if I want to connect to it at a later time?

lzgirlcat commented 1 year ago

I've been using this

from peewee_aio.manager import Manager as _Manager
from peewee_aio.databases import get_db
from peewee import DatabaseProxy, logger
from weakref import WeakSet

class Database(_Manager):
    def __init__(self):
        self.url = None
        self.backend_options = {}
        self.pw_database = DatabaseProxy()

    def init(self, url: str | None = None, **backend_options):
        if not url and not self.url:
            raise ValueError("DB url was never given!")
        backend_options.setdefault("convert_params", True)
        self.backend_options.update(backend_options)
        super(_Manager,self).__init__(url or self.url, logger=logger, **self.backend_options)

        self.models = WeakSet()
        self.pw_database.initialize(get_db(self))

and then

db = Database()

class BaseModel(AIOModel):
    __rel__: dict[str, Self]
    _manager = db

    class Meta:
        database = db.pw_database

class User(BaseModel):
    name = f.CharField()

...

db.init(db_url)