How to create all tables defined in models using peewee

I define many model classes using peewee. ClassName.create_table() can generate a table, but only one table. How can I create all tables using a single statement?

+6
source share
5 answers

Extension of coleifer answer with the assumption that all tables are grouped into one module:

 import inspect import peewee import tables models = [ obj for name, obj in inspect.getmembers( tables, lambda obj: type(obj) == type and issubclass(obj, peewee.Model) ) ] peewee.create_model_tables(models) 
+8
source

Peewee has a helper that will create the tables in the correct order, but you still need to explicitly pass all the models:

 from peewee import * db = SqliteDatabase(':memory:') db.create_tables([ModelA, ModelB, ModelC]) 
+9
source

This snipnet will create all the tables whose objects are defined in the current module:

 import sys for cls in sys.modules[__name__].__dict__.values(): try: if BaseModel in cls.__bases__: cls.create_table() except: pass 
+1
source
 for cls in globals().values(): if type(cls) == peewee.BaseModel: try: cls.create_table() except peewee.OperationalError as e: print(e) 
0
source

An update for Python 3 (and anyone who comes across this question through Google, how I did it). If you have all the models based on the main class of the Peewee model, you can simply use:

 import peewee models = peewee.Model.__subclasses__() 

Confirm this question for this idea. They also discuss in detail how to make it work recursively if your model is more complex.

0
source

All Articles