Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SqlAlchemy: Inspect/Reflect information about relationship

I have a sqlalchemy class R which implements a m:n relation between two other classes A and B. So R has two integer columns source_id and target_id which hold the ids of the referenced instances. And R has two properties source_obj and target_obj which are defined via relationship. It's more or less the same as decribed here in the documenation.

What I want to do is to retrieve the referenced classes from R. I'm using sqlalchemy 0.8 and tried to use the inspect() method on R.source_obj, but I only get back a InstrumentedAttribute which seems not to be of much help. At least I was not able to extract any useful information or to find any documentation about it.

Any help would be very appreciated! How do I get A and B from R?

like image 565
Achim Avatar asked Sep 14 '12 22:09

Achim


1 Answers

Try something like this. I'm also dealing with this and find no documentation, think this can help you to start.

from sqlalchemy import inspect

i = inspect(model)
for relation in i.relationships:
    print(relation.direction.name)
    print(relation.remote_side)
    print(relation._reverse_property)
    dir(relation)
like image 65
Gustavo Gonçalves Avatar answered Sep 28 '22 01:09

Gustavo Gonçalves