I think the simplest solution is using a factory for the models.
def models_factory(database):
class Model1(Model):
class Meta:
database = database
...
...
return(locals().copy())
somewhere else:
models = models_factory(database)
models['Model1'].create_table()
The function creates all the models using the database passed as argument. Then returns locals()
dict which contains all the models defined.
If you use ForeignKeyField
then it is important that the referenced model is defined in the same function or that it is defined in the calling scope.
Alternatively you can use DeferredForeignKey
if you want to define the models in different functions (factories):
def model1(database):
class Model1(Model):
...
return Model1
def model2(database)
class Model2(Model):
model1_id = DeferredForeignKey('Model1', field='id', ...)
...
return Model2
somewhere else:
Model1 = model1(database)
Model2 = model2(database)
Also if you are using multiple databases with the same database structure you can create a Database
class inherited from peewee database and define the factory/es as methods.
Then you could instantiate the database just as Database(filename)
and you have all the models in there:
class Database(SqliteDatabase):
def __init__(self, filename):
super().__init__(filename, pragmas={'foreign_keys': 1})
self.models = self.create_models()
...
def create_models(self)
class Model1(Model):
class Meta:
database = self
...
...
return locals().copy()
somewhere else:
db = Database("mydatabase.db")
db.models['Model1'].create_table()