admin管理员组文章数量:1295887
Using SqlAlchemy 1.4, in a FastAPI application, I have the need to import all the models before doing Base.metadata.create_all()
. There are many tables with multiple relatinoships.
How should I do to import all the tables? I have 2 working solutions right now:
1.add all the imports in a __init__.py
file in some module that I'm sure will be always imported (I can't do this in a main file because the project has a different main file per environment). in this approach all the FK are declared in the following way:
class TableA(Base):
table_b = relatonship("TableB")
class TableB(Base):
table_a = relatonship("TableA")
- in every table that has a relationship, try to import the related table, so, for example if I have TableA and TableB, and TableA has a FK to TableB.
in table_a.py:
from models.table_b import TableB
class TableA(Base):
table_b = relatonship(TableB)
in table_b.py:
class TableB(Base):
table_a = relatonship("TableA")
In TableB the relationship can't import TableA due to circular imports.
I'm not sure which approach is best, and I can't find any standard for this
I already looked it up for other projets with similar set ups, but are always too simple compared to what I'm trying to do, usually with almost no relationships. I also tested the options that I asked and both works, but as I explained, not sure which one is better
本文标签: pythonBest way to declare sqlalchemy tablesStack Overflow
版权声明:本文标题:python - Best way to declare sqlalchemy tables - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741626307a2389103.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论