让我们有一个类 X 和 Y 以及它们之间的关系 x2y 和 y2x。 从 class_mapper(Class).iterate_properties 迭代器我们可以获得所有类的属性。 所以 x2y 和 y2x 是 RelationshipProperty,我希望从中得到的是关系远端对象的类或类名。
我已经尝试过解决方案。
我找到了 x2y.remote_side[0].table.name
,制作了一个 tables_map,它将表名映射到一个类,它适用于一对多和一对一。如果我将它用于多对多,则表名是一个关联表。
关于如何获取远程端类的任何提示?
最佳答案
X.x2y.property.mapper.class_
relatonshipproperty 最终将获得类级别的属性文档,就像现在的 mapper 一样。
编辑。这是一个说明上述从“X”返回“Y”的测试,没有反射不会创建关系,因此应该没有效果:
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
关于python - 如何在没有数据库查询的情况下找到 sqlalchemy 远程端对象的类或类名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6843144/