Get related models in SQLAlchemy

2020-07-18 03:31发布

问题:

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.).

回答1:

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.