Search code examples
pythonsqlitepeewee

Do i need to call create tables every time in peewee?


I working in a project in which i have different projects with the same database architecture, so i used peewee Model in which:

dynamic_db = SqliteDatabase(None)
class BaseModel(Model):
    class Meta:
        database = dynamic_db
class KV (BaseModel):
    key = TextField()
    value = IntegerField()

And whenever i new project is created i will call a function

dynamic_db.init(r'{}\database.db'.format(ProjectName.upper()))
dynamic_db.connect()
dynamic_db.create_tables([KV])
dynamic_db.close()

The problem is that once this database is created, i can't access with peewee. When i try to create a record:
KV.create(key = 'Saul', value = 123)
I get this error:
peewee.InterfaceError: Error, database must be initialized before opening a connection.

I would appreciate any help or cookbook for peewee.


Solution

  • I believe something is incorrect, either in your question description, or in the error you are receiving. The call you are making to .init() is what initializes the database. After that, you should have no problems using it.

    Full example which works fine:

    from peewee import *
    
    db = SqliteDatabase(None)
    
    class Base(Model):
        class Meta:
            database = db
    
    class KV(Base):
        key = TextField()
        value = IntegerField()
    
    db.init('foo.db')  # database is now initialized
    db.connect()
    db.create_tables([KV])  # no problems.
    db.close()