【问题标题】:How do I get a related Model instance by PK from an ORM Model?如何通过 PK 从 ORM 模型中获取相关模型实例?
【发布时间】:2016-08-28 08:47:44
【问题描述】:

我有一个 SQLAlchemy 模型类 model,一个表示属性/列 attr 的字符串,对应于与另一个模型类 othermodel 的 ORM 关系,以及一个私钥或 id这样一个othermodel的字符串。

我想找到对象 othermodel.get(id) 将其存储在新构造的实例中,使用类似 setattr(model(), attr, ???) - 但我没有那个 othermodel 可在变量中访问。我怎么得到它?

我假设我可以对 model 或其新实例使用某种内省,但如何?

【问题讨论】:

    标签: sqlalchemy


    【解决方案1】:

    挖掘 model的属性,我在

    中找到了othermodel的副本
    getattr(model, attr).comparator.property.argument
    

    把我的任务变成

    setattr(model(), attr, getattr(model, attr).comparator.property.argument.get(id))
    

    真是一口! 目前这看起来很合理,但我很确定我错过了一种更明显的访问方式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-03
      • 2019-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多