我需要得到这实际上关系模型的属性列表(即,他们被relationship()
创建)。
说我有一个Foo
模型models
:
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
。上的映射类调用inspect
(例如,您Thing
类)将返回一个Mapper
,其中有一个relationships
属性是dict
这样的:
from sqlalchemy.inspection import inspect
thing_relations = inspect(Thing).relationships.items()
而不是使用inspect
你也可以使用的
model.__mapper__.relationships
你只需要使用从inspect
的sqlalchemy
模块
from sqlalchemy import inspect
i = inspect(model)
i.relationships
如果你需要的类均称为模型,你可以这样做:
referred_classes = [r.mapper.class_ for r in i.relationships]