SQL炼金术关系内省

2024-04-23 10:20:51 发布

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

我有两个具有一对多关系的映射类:

class Part(...):
    product = relationship('products', backref=backref('parts'))

class Product(...):
    pass

给定Part.product,我可以反省这种关系,即获得属性名,也可以得到backref属性名:

^{pr2}$

我也可以从另一个角度了解这种关系:

>>> rel = Product.parts
>>> rel
<sqlalchemy.orm.attributes.InstrumentedAttribute object at 0x3744fd0>
>>> rel.property.key
'parts'

但是,我无法找到如何访问原始属性名(在示例中又称backref'backref属性,又称为“product”):

>>> rel.property.backref is None
True

我要在哪里挠Product.parts才能得到{}?在


Tags: 属性关系propertypassproductclassproductsrel
1条回答
网友
1楼 · 发布于 2024-04-23 10:20:51

我试着重现你描述的情况,也得到了Product.parts.property.backref = None。 在pycharm中调试后,我发现其他属性的部分名称为:

print Product.parts.property.backref
>>>None
print Product.parts.property.back_populates
>>>product

我建议考虑在本例中使用back_populates作为黑客。在

后台填充在documentation Linking Relationship Configuration:Relationships with Backref中描述。根据文档,您需要这样定义模型:

^{pr2}$

相关问题 更多 >