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")
  1. 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