How do I split models.py into different files for different models in Pyramid?

放肆的年华 提交于 2019-11-30 00:41:27
myapp
    __init__.py
    scripts
        __init__.py
        initialize_db.py
    models
        __init__.py
        meta.py
        foo.py
        moo.py

now meta.py can contain a shared Base as well as the DBSession:

Base = declarative_base()
DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension))

Each foo.py and moo.py can import their shared base from meta.py.

from .meta import Base

class Foo(Base):
    pass

To ensure that all of your tables are picked up, from within the models subpackage, and for convenience, you can import them into models/__init__.py:

from .meta import DBSession
from .foo import Foo
from .moo import Moo

Without doing something like this the different tables will not be attached to the Base and thus will not be created when create_all is invoked.

Your initialize_db script can then create all of the tables via

from myapp.models.meta import Base
Base.metadata.create_all(bind=engine)

Your views can import the models to profit:

from myapp.models import DBSession
from myapp.models import Foo

I had the same problem once.

The solving for the splited model files: you must initialize all Base (parent) classes from your files separately:

#initializedb.py
...
from project.models.Foo import Base as FooBase
from project.models.Moo import Base as MooBase
...

def main(argv=sys.argv):
    ...
    FooBase.metadata.create_all(engine)
    MooBase.metadata.create_all(engine)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!