Database Creation #79

maxekman opened this Issue May 5, 2012 · 5 comments


None yet

2 participants


I need to read in the db config from a file which currently does not work with the way the Meta class is used. It creates a default "peewee.db" if the database attribute is not set when parsing the model classes. Could this be delayed until a Model is actually used?

I just read this thread on the mailing list about the same issue and wondered if this patch (or similar) could be applied to the main branch?



I've been thinking about how to fix this... I'm going to assume that a model is "actually used" whenever the db connection is either explicitly or implicitly opened. If that's the case, then it really isn't a problem to structure your code such that you modify the underlying db connection on-the-fly. The most important thing is that you don't want a bunch of Database instances running around, since each will open its own connection to the server -- in other words, there should be only one Database for each database you intend to connect to.

What I think I'll do is allow a user to set a db to "deferred" when initializing, then if you attempt to connect to the db (either by explicitly calling connect() or by trying to issue a query) it will raise an exception if the db hasn't been properly initialized.

@coleifer coleifer closed this in dbe34ea May 9, 2012

If readthedocs ever updates, you can find docs here -- the basic idea is passing None as the db name will mark the db as deferred and an exception will be raised if you try and use it. You can then properly init the db by calling db.init():

>>> db = SqliteDatabase(None)
>>> db.deferred

>>> db.connect()
Exception raised

>>> db.init(':memory:')
>>> db.connect()

Very nice, I'll give this a try later. Is it published to pypi yet?


Just pushed a new version, 0.9.6 -- let me know how it works out!


This works perfectly!

The new best practice is probably to use a uninitialized db in the base model:

class BaseModel(peewee.Model):
    class Meta:
        database = peewee.SqliteDatabase(None)

And later init it:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment