我需要获取模型的属性列表,这些属性实际上是关系(也就是说,它们是由 relationship()
创建的)。
假设我在 models
中有一个模型 Foo
:
class Thing(db.Model):
id = db.Column(...)
bar_id = db.Column(...)
foo_id = db.Column(...)
foo = db.relationship('Foo')
bar = db.relationship('Bar')
稍后,我想采用 models.Thing
并获取关系属性列表,即 ['foo', 'bar']
。
目前我正在检查 dir(models.Thing)
指示的每个属性恰好是类型 sqlalchemy.orm.attributes.InstrumentedAttribute
的类property
属性 — 可以是 ColumnProperty
或 RelationshipProperty
。这样就可以了,但我想知道是否还有其他方法。
我可能只找到所有以 _id
结尾的属性并导出关系名称,但在某些情况下这可能会中断。
如何设置 __relationships__ = ['foo', 'bar']
?
或者 SQLAlchemy 中是否有内置的东西可以帮助我?
最佳答案
确实有-看看sqlalchemy.inspection.inspect
.在映射类(例如,您的 Thing
类)上调用 inspect
将返回 Mapper
,它有一个 relationships
dict
的属性如下:
from sqlalchemy.inspection import inspect
thing_relations = inspect(Thing).relationships.items()
关于python - SQLAlchemy:从 db.Model 获取关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21206818/