【问题标题】:SQLAlchemy relationship introspectionSQLAlchemy 关系自省
【发布时间】:2013-01-18 12:05:47
【问题描述】:

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

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

class Product(...):
    pass

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

>>> rel = Part.product   # image it's passed in as a function parameter
>>> rel.property.key
'product'
>>> rel.property.backref[0]
'parts'

我也可以反过来访问关系:

>>> 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 才能获得'product'

【问题讨论】:

    标签: python sqlalchemy introspection


    【解决方案1】:

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

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

    在这种情况下,我建议考虑使用back_populates 作为黑客攻击。

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

    class Part(...):
        product = relationship('products', back_populates='parts')
    
    class Product(...):
        parts = relationship('products', back_populates='product')
        pass
    

    【讨论】:

    • 太棒了,正是我需要的 :-) 我什至不认为这是一个 hack,它看起来像是查找属性名称的规范方法(backref 是设置 back_populates 的快捷方式)。感谢您解决这个问题!
    猜你喜欢
    • 1970-01-01
    • 2011-07-20
    • 2023-03-17
    • 1970-01-01
    • 2013-10-22
    • 2011-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多