9

Let's have a classes X and Y and relations between them x2y and y2x. From class_mapper(Class).iterate_properties iterator we can get all class's properties. So x2y and y2x are RelationshipProperty and what I hope to get from is a class or a class name of objects on remote side of relation.

I've already tried to make a solution. I've found x2y.remote_side[0].table.name, made a tables_map which maps a table name to a class and it works fine for one-to-many and one-to-one. If I use it for many-to-many the table name is an association table.

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

mdob
  • 2,224
  • 3
  • 22
  • 25

2 Answers2

30

X.x2y.property.mapper.class_

relatonshipproperty will eventually get class-level attribute documentation the same as mapper does now.

edit. Here is a test which illustrates the above returning "Y" from "X", and no reflection doesn't create relationships so 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
zzzeek
  • 72,307
  • 23
  • 193
  • 185
3

I've found that a method argument() on relationshipproperty returns remote class.

for prop in class_mapper(X).iterate_properties:
    if isinstance(prop, RelationshipProperty):
        relation = prop
relation.argument()
mdob
  • 2,224
  • 3
  • 22
  • 25
  • 2
    argument() is only what's been passed to the relationship() function originally and is not necessarily a callable. "mapper" is the mapper which the relationship refers to. – zzzeek Aug 08 '11 at 05:02