Get related models in SQLAlchemy

I have different models fettered in SQLAlchemy (there are many, belongs, etc.). Is there a way to find related models based on instance?

Sort of:

usersModelInstance.getRelatedTables() // This should provide an array or something with the related tables of users (orders, logins, posts, etc.). 
+4
source share
1 answer

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

In either case, first create a property list for your mapped object:

 # Import sqlalchemy so we can use it import sqlalchemy as sa # Rename the OP 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 do not currently have an object instance handle, but only a mapped class.

Now, in the first case, when you need a list of related tables, do:

 related_tables = [prop.target for prop in relation_properties] 

In the second case, when you may need a list of related mapped classes, do:

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

Hope this helps you get started.

+8
source

All Articles