Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create all tables defined in models using peewee

Tags:

python

orm

peewee

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

like image 861
Alexander.Li Avatar asked Feb 07 '14 15:02

Alexander.Li


6 Answers

An update for Python 3 (and everyone who comes across this question via Google like I did). If you have all models based on the main peewee Model class you can simply use:

import peewee    
models = peewee.Model.__subclasses__()

Credit to this question for the idea. They also go into more detail on how to get it to work recursively if your model is more complex.

like image 64
ninetynine Avatar answered Dec 25 '22 01:12

ninetynine


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

from peewee import *
db = SqliteDatabase(':memory:')
db.create_tables([ModelA, ModelB, ModelC])
like image 20
coleifer Avatar answered Dec 25 '22 00:12

coleifer


Extending coleifer's answer with the assumption that all tables are grouped in 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)
like image 22
Cilyan Avatar answered Dec 25 '22 01:12

Cilyan


This snipnet will create all tables which 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
like image 28
Mathieu Rodic Avatar answered Dec 25 '22 00:12

Mathieu Rodic


for cls in globals().values():
    if type(cls) == peewee.BaseModel:
        try:
            cls.create_table()
        except peewee.OperationalError as e:
            print(e)
like image 24
thinker3 Avatar answered Dec 25 '22 01:12

thinker3


def create_all_tables():
    for cls in sys.modules[__name__].__dict__.values():
        if hasattr(cls, '__bases__') and issubclass(cls, peewee.Model):
            if cls is not BaseModel:
                cls.create_table()

This also works for ManyToManyField's get_through_model().

like image 20
Polv Avatar answered Dec 25 '22 00:12

Polv