I want to use sqlalchemy declarative_base to create all tables and relations for my database, however, I have separated my models across multiple files and now fail to find a suitable architecture to use it.
Calling declarative_base returns a object which the models need to use as base class. However, it returns a new object every time it is called and the object needs to be the same for all models for it to work.
I have defined a small method for a database manager class which should construct the database. Naturally, for this to work the Base needs to be the same instance as used in all the models:
engine = sqlalchemy.create_engine("sqlite:///%s" % file)
create_database(engine.url) #sqlalchemy-utils
Base.metadata.create_all(engine) # declarative_base
The problem arises at all my solutions either violating PEP F401 due to unused imports or causing circular dependencies. If I do not import the models without using them the class will not be defined using declarative_base and it won't be added to the database. While importing the models without using them will violate F401.
I fail to see how to create a clean construct with a shared declarative_base for all the models and the database manager without having unused imports. How can an instance of declarative_base be shared across models and database manager in such a way all tables will be created without unused imports?
from How to properly use sqlalchemy declarative_base with multiple model files
No comments:
Post a Comment