Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am new to pyramid and have been struggling to make some changes to my project. I am trying to split my models/Classes into individual files instead of a single models.py file. In order to do so I have removed the old models.py and created a models folder with __init__.py file along with one file for each class. In __init__.py I imported the class by using from .Foo import Foo.

This makes the views work correctly and they can initialize an object.

But running the initializedb script does not create new tables as it did when I had all the models in a single models.py. It does not create the relevant tables but directly tries to insert in them.

Can anyone give me an example of a pyramid project structure which has models in different files?

like image 652
Karan Avatar asked Apr 27 '12 06:04

Karan


Video Answer


1 Answers

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
like image 85
Michael Merickel Avatar answered Oct 07 '22 00:10

Michael Merickel