Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get related models in SQLAlchemy

I have various models chained in SQLAlchemy (has many, belongs to, etc.). Is there a way of finding the related models given ones instance?

Something like:

usersModelInstance.getRelatedTables() // This should provide an array or something with the related tables of users (orders, logins, posts, etc.).
like image 225
ian P. Avatar asked Jan 19 '23 14:01

ian P.


1 Answers

I'm not sure quite what you want -- a list of tables or a list of mapped classes?

In either case, first build a list of properties for your mapped object:

# Import sqlalchemy so we can use it
import sqlalchemy as sa

# Rename the OP's object to `obj`
obj = usersModelInstance

# Build a list of only relationship properties
relation_properties = filter(
    lambda p: isinstance(p, sa.orm.properties.RelationshipProperty),
    sa.orm.object_mapper(obj).iterate_properties
)

Note that you can use the sa.orm.class_mapper(cls) function if you don't currently have a handle on an entity instance, but only a mapped class.

Now, in the first case where you want a list of the related tables, do:

related_tables = [prop.target for prop in relation_properties]

In the second case where you might want a list of the related mapped classes, do:

related_classes = [prop.mapper.class_ for prop in relation_properties]

Hopefully this can get you started.

like image 129
threebean Avatar answered Jan 28 '23 14:01

threebean