Achim
Achim

Reputation: 15692

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?

Upvotes: 8

Views: 3825

Answers (2)

Gustavo Gonçalves
Gustavo Gonçalves

Reputation: 493

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)

Upvotes: 6

ohsully
ohsully

Reputation: 502

I spent the majority of the day working on this same problem, and I was able to write a list comprehension that takes in a table and then spits out a list of the table names which are connected via a relationship or a foreign key. You need to convert that string into a reference to the actual class, but otherwise it works just fine.

relationship_list = [str(list(column.remote_side)[0]).split('.')[0] for column \
                    in inspect(table).relationships]

By removing the .split('.')[0], you can get a list of the actual columns which are referred to by the connections. The comprehension is pretty ugly, but it works. Hope this helps anyone else who is looking for the same thing I was!

Upvotes: 0

Related Questions