How to discover table properties from SQLAlchemy mapped object

你。 提交于 2019-11-26 10:58:18

问题


I have a class mapped with a table, in my case in a declarative way, and I want to \"discover\" table properties, columns, names, relations, from this class:

engine = create_engine(\'sqlite:///\' + databasePath, echo=True)

# setting up root class for declarative declaration
Base = declarative_base(bind=engine)

class Ship(Base):
    __tablename__ = \'ships\'

    id = Column(Integer, primary_key=True)
    name = Column(String(255))

    def __init__(self, name):
            self.name = name

    def __repr__(self):
            return \"<Ship(\'%s\')>\" % (self.name)

So now my goal is from the \"Ship\" class to get the table columns and their properties from another piece of code. I guess I can deal with it using instrumentation but is there any way provided by the SQLAlchemy API?


回答1:


Information you need you can get from Table object:

  • Ship.__table__.columns will provide you with columns information
  • Ship.__table__.foreign_keys will list foreign keys
  • Ship.__table__.constraints, Ship.__table__.indexes are other properties you might find useful


来源:https://stackoverflow.com/questions/2441796/how-to-discover-table-properties-from-sqlalchemy-mapped-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!