如何在没有数据库查询的情况下找到sqlalchemy远程对象的类或类名?

2024-10-03 09:16:09 发布

您现在位置:Python中文网/ 问答频道 /正文

让我们有一个类X和Y,以及它们之间的关系。 从类映射器(class.iterate\u properties iterator)我们可以得到所有类的属性。 所以x2y和y2x是RelationshipProperty,我希望从关系的远程端得到一个类或一个对象的类名。在

我已经想办法解决了。 我找到了x2y.remote_side[0].table.name,制作了一个表映射,它将一个表名映射到一个类上,并且它对于一对多和一对一都很好。如果我将它用于多对多,那么表名就是一个关联表。在

有什么关于我如何获得远程旁听课的提示吗?在


Tags: 对象属性远程remote关系propertiessideclass
2条回答

X.x2y。property.mapper.class\在

relationshipproperty最终将获得类级别的属性文档,就像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

我发现relationshipproperty上的方法参数()返回远程类。在

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

相关问题 更多 >