【问题标题】:SQLAlchemy: get relationships from a db.ModelSQLAlchemy:从 db.Model 获取关系
【发布时间】:2014-01-18 16:36:40
【问题描述】:

我需要获取一个模型属性列表,这些属性实际上是关系(也就是说,它们是由relationship() 创建的)。

假设我在models 中有一个模型Foo

class Thing(db.Model):
    id = db.Column(...)
    bar_id = db.Column(...)
    foo_id = db.Column(...)
    foo = db.relationship('Foo')
    bar = db.relationship('Bar')

稍后,我想获取models.Thing 并获取关系属性列表,即['foo', 'bar']

目前,我正在检查dir(models.Thing) 指示的每个属性,这些属性恰好是sqlalchemy.orm.attributes.InstrumentedAttribute 类型的property 属性类——可以是ColumnPropertyRelationshipProperty。这可以完成工作,但我想知道是否还有其他方法。

我可能只找到所有以 _id 结尾的属性并派生关系名称,但在某些情况下这可能会中断。

设置一个__relationships__ = ['foo', 'bar']怎么样?

或者 SQLAlchemy 中是否有内置的东西可以帮助我?

【问题讨论】:

    标签: python sqlalchemy


    【解决方案1】:

    确实有 - 看看sqlalchemy.inspection.inspect。在映射类(例如,您的 Thing 类)上调用 inspect 将返回一个 Mapper,它的 relationships 属性是 dict,例如:

    from sqlalchemy.inspection import inspect
    
    thing_relations = inspect(Thing).relationships.items()
    

    【讨论】:

    • 有没有一种简单的方法可以同时查看“Foo”和“Bar”?
    • 不确定您的意思 - 值得提出一个新问题并链接到该问题以获取上下文。
    • 编辑添加.items(),因为我发现自己有一个 sqlalchemy.util._collections.ImmutableProperties 并且它不是很有帮助(我的意思是上课时,它不会打印)。他想要一份清单。
    【解决方案2】:

    你也可以使用inspect来代替

    model.__mapper__.relationships

    【讨论】:

      【解决方案3】:

      您只需要使用来自sqlalchemyinspect 模块

      from sqlalchemy import inspect
      
      i = inspect(model)
      i.relationships
      

      如果您需要每个引用模型的类,您可以这样做:

      referred_classes = [r.mapper.class_ for r in i.relationships]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-23
        • 2022-08-24
        • 2018-12-20
        • 2016-12-10
        • 2013-05-03
        • 2013-10-22
        相关资源
        最近更新 更多