I want to separate my model classes into separate files in a models directory. I would like to have a separate file for:
- general (authentication and global classes/tables)
- requisitions (tables used for requisitions)
- workorders (tables used for workorders)
- sales_orders (tables used for sales orders)
- ...etc
I'm not sure how to structure my project to make that happen.
I've tried putting my main imports into init.py in the directory and them importing those into the individual model files, but I don't know where to put my db.generate_mapping() so that all classes are available. I'm guessing this is a best practice for a large application. I've got about 150 tables in my app at this point.
Any help/pointers would be appreciated.
You can use the following project structure:
settings.py
is a file with database settings:main.py
is a file when you start application. You putdb.generate_mapping
here:Note that it is not necessary to implicitly import all models, as they are accessible as attributes of
db
object (likedb.User
)You can put
db
object inbase.py
(orgeneral.py
), where you define your core models:Note that in
User
model I can refer toOrder
model defined in another module. You can also write it asUnfortunately, IDEs like PyCharm at this moment cannot recognize that
db.Order
refers to specificOrder
class. You can import and useOrder
class directly, but in some cases it will lead to problem with cyclic imports.In other model files you import
db
from.base
:In
/models/__init__.py
you import all modules to ensure that all models classes are defined beforegenerate_mapping
is called:And then you can write
And access models as
db
attributes likedb.User
,db.Order
, etc.If you want to refer models directly in your code instead of accessing them as
db
attributes, you can import all models in__init__.py
:And then you can import model classes as: