本文介绍了如何从SQLAlchemy映射对象发现表属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用表声明的方式映射到一个表的类,并且我想从此类中发现"表的属性,列,名称,关系:

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)

所以现在我的目标是从"Ship"类中从另一段代码中获取表列及其属性.我想我可以使用工具来处理它,但是SQLAlchemy API是否提供任何方式?

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?

推荐答案

您需要的信息可以从表格对象:

Information you need you can get from Table object:

  • Ship.__table__.columns将为您提供列信息
  • Ship.__table__.foreign_keys将列出外键
  • Ship.__table__.constraintsShip.__table__.indexes是您可能会发现有用的其他属性
  • 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

这篇关于如何从SQLAlchemy映射对象发现表属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 10:54