【问题标题】:How can I create a SQLAlchemy query containing only instances related to a specific instance of a model?如何创建仅包含与模型的特定实例相关的实例的 SQLAlchemy 查询?
【发布时间】:2015-10-20 18:46:51
【问题描述】:

我得到了一个 SQLAlchemy 模型 instance 的实例以及该实例上的关系名称 relation。我可以通过getattr(instance, relation) 访问所有相关实例。如何构造一个包含该关系的所有实例的查询,或者换句话说,一个计算结果为getattr(instance, relation) 的查询?我没有得到有关数据库表等的其他信息。

这类似于问题Construct a query to filter many-to-many for all B instances related to a given A instance,但我没有表定义。

【问题讨论】:

    标签: python sqlalchemy introspection


    【解决方案1】:

    我的解决方案如下。假设instance是模型的一个实例,relation是表示该模型关系属性的字符串,'id'是相关模型的主键,related_model是相关模型。此解决方案仅根据给定实例的一对多关系属性中主键在已知主键列表中的那些实例过滤相关模型:

    relationship = getattr(instance, relation)
    primary_keys = {getattr(inst, 'id') for inst in relationship}
    query = session.query(related_model)
    query.filter(getattr(related_model, 'id') in primary_keys)
    

    【讨论】:

      猜你喜欢
      • 2012-03-18
      • 2011-01-29
      • 1970-01-01
      • 2019-02-25
      • 2013-03-29
      • 2011-08-11
      • 2015-01-09
      • 2019-08-01
      • 2018-03-21
      相关资源
      最近更新 更多