python 如何从 SQLAlchemy 映射对象中发现表属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2441796/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to discover table properties from SQLAlchemy mapped object
提问by Olivier Girardot
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?
所以现在我的目标是从“Ship”类中从另一段代码中获取表列及其属性。我想我可以使用检测来处理它,但是 SQLAlchemy API 是否提供了任何方法?
回答by van
Information you need you can get from Tableobject:
您可以从Table对象中获取您需要的信息:
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
Ship.__table__.columns
将为您提供栏目信息Ship.__table__.foreign_keys
将列出外键Ship.__table__.constraints
,Ship.__table__.indexes
您可能会发现其他有用的属性