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
. Callinginspect
on a mapped class (for example, yourThing
class) will return aMapper
, which has arelationships
attribute that isdict
like:You just need to use the
inspect
module fromsqlalchemy
If you need the class of each referred model you can do:
Instead of using
inspect
you can also usemodel.__mapper__.relationships