How to find sqlalchemy remote side feature class or class name without db queries?

Let the classes X and Y and the relations between them be x2y and y2x. From the iterator class_mapper (Class) .iterate_properties we can get all the properties of the class. So, x2y and y2x are RelationshipProperty, and I hope to get from it the class or class name of the objects on the far side of the relationship.

I already tried to make a decision. I found x2y.remote_side[0].table.name , made table_map, which maps the table name to the class and works great for one-to-many and one-to-one. If I use it for many-to-many, the table name is the association table.

Any tips on how I can get the remote side class?

+7
source share
2 answers

X.x2y.property.mapper.class _

relatonshipproperty will eventually receive class level attribute documentation similar to what mapper now does.

to change. Here is a test that illustrates the above return of “Y” from “X”, and no reflection creates a relationship, so it should have no effect:

 from sqlalchemy import Column, Integer, ForeignKey from sqlalchemy.orm import relationship from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class X(Base): __tablename__ = 'x' id = Column(Integer, primary_key=True) x2y = relationship("Y") class Y(Base): __tablename__ = 'y' id = Column(Integer, primary_key=True) x_id = Column(Integer, ForeignKey("x.id")) assert X.x2y.property.mapper.class_ is Y 
+18
source

I found that the method argument () for the property relation returns a remote class.

 for prop in class_mapper(X).iterate_properties: if isinstance(prop, RelationshipProperty): relation = prop relation.argument() 
+1
source

All Articles