如何从 SQLAlchemy 映射对象发现表属性
我有一个与表映射的类,在我的例子中是以声明的方式,我想从这个类中“发现”表属性、列、名称、关系:
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 是否提供了任何方法?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以从 Table 对象获取所需的信息:
Ship.__table__.columns
将为您提供列信息Ship.__table__.foreign_keys
将列出外键Ship.__table__.constraints
,Ship.__table__.indexes
是您可能会发现有用的其他属性Information you need you can get from Table object:
Ship.__table__.columns
will provide you with columns informationShip.__table__.foreign_keys
will list foreign keysShip.__table__.constraints
,Ship.__table__.indexes
are other properties you might find useful如果未使用声明性基础,则答案将失败。无论如何初始化,以下内容都应该有效
对于类对象:
对于实例对象:
If declarative base is not used, the answer fails. The following should work no matter how it's initialized
For Class Object:
For Instance Object: