SQLAlchemy,Flask:从db.Model获取关系 [英] SQLAlchemy, Flask: get relationships from a db.Model
问题描述
我需要得到一个模型属性的列表,这些属性实际上是关系的(也就是说,它们是由 relationship()
)创建的。 b
假设我在模型
中有一个模型 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)
code> sqlalchemy.orm.attributes.InstrumentedAttribute 为它的属性的类
属性 - 可以是 ColumnProperty
或 RelationshipProperty
。这样做的工作,但我想知道是否有另一种方式。
我可能只是找到所有以 _id
和派生关系名称,但这可能会打破一些情况下。
如何设置 __ relationships__ = ['foo','bar' ]
?
或者是在SQLAlchemy中内置了哪些东西来帮助我?
确实有 - 请看 sqlalchemy.inspection.inspect
。在映射类(例如, Thing
类)上调用 inspect
将返回一个 Mapper
,它有一个< a href =http://docs.sqlalchemy.org/en/rel_0_9/orm/mapper_config.html#sqlalchemy.orm.mapper.Mapper.relationships> 关系
属性:
from sqlalchemy.inspection import inspect
thing_relations = inspect(Thing)。关系
I need to get a list of a model's properties which are actually relationships (that is, they were created by relationship()
).
Say I have a model Foo
in a models
:
class Thing(db.Model):
id = db.Column(...)
bar_id = db.Column(...)
foo_id = db.Column(...)
foo = db.relationship('Foo')
bar = db.relationship('Bar')
Later on, I want to take models.Thing
and get a list of relationship-properties, that is ['foo', 'bar']
.
Currently I'm checking every attribute indicated by dir(models.Thing)
that happens to be of type sqlalchemy.orm.attributes.InstrumentedAttribute
for the class of its property
attribute — which can be either a ColumnProperty
or RelationshipProperty
. This does the job but I was wondering if there's another way.
I could probably just find all attributes ending in _id
and derive the relationship name, but this could break for some cases.
How about setting a __relationships__ = ['foo', 'bar']
?
Or is there something built into SQLAlchemy to help me out?
There is indeed - take a look at sqlalchemy.inspection.inspect
. Calling inspect
on a mapped class (for example, your Thing
class) will return a Mapper
, which has a relationships
attribute:
from sqlalchemy.inspection import inspect
thing_relations = inspect(Thing).relationships
这篇关于SQLAlchemy,Flask:从db.Model获取关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!