SQLAlchemy:从 db.Model 获取关系 [英] SQLAlchemy: get relationships from a db.Model
问题描述
我需要获取模型属性的列表,这些属性实际上是关系(也就是说,它们是由 relationship()
创建的).
I need to get a list of a model's properties which are actually relationships (that is, they were created by relationship()
).
假设我在 models
中有一个模型 Foo
:
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')
稍后,我想使用 models.Thing
并获得一个关系属性列表,即 ['foo', 'bar']
.
Later on, I want to take models.Thing
and get a list of relationship-properties, that is ['foo', 'bar']
.
目前我正在检查 dir(models.Thing)
指示的每个属性,这些属性恰好是 sqlalchemy.orm.attributes.InstrumentedAttribute
类型的property
属性 — 可以是 ColumnProperty
或 RelationshipProperty
.这样做可以,但我想知道是否还有其他方法.
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.
我可能只需找到以 _id
结尾的所有属性并导出关系名称,但在某些情况下这可能会中断.
I could probably just find all attributes ending in _id
and derive the relationship name, but this could break for some cases.
如何设置 __relationships__ = ['foo', 'bar']
?
或者 SQLAlchemy 中是否有内置的东西来帮助我?
Or is there something built into SQLAlchemy to help me out?
推荐答案
确实有 - 看看 sqlalchemy.inspection.inspect
.在映射类(例如,您的 Thing
类)上调用 inspect
将返回 Mapper
,它有一个 relationships
属性,即 dict
喜欢:
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 that is dict
like:
from sqlalchemy.inspection import inspect
thing_relations = inspect(Thing).relationships.items()
这篇关于SQLAlchemy:从 db.Model 获取关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!