【问题标题】:SqlAlchemy Select Relation TypeSqlAlchemy 选择关系类型
【发布时间】:2010-11-01 17:35:54
【问题描述】:

我有一个用 SqlAlchemy 映射的简单的一对多关系:

Base = declarative_base()

class Type(Base):

    __tablename__ = "entity_types"

    type = Column(String(100), primary_key=True)
    description = Column(String(300))

class Entity(Base):

    __tablename__ = "entities"

    id = Column(Integer, primary_key=True)
    type_id = Column('type', String(100), ForeignKey(Types.type), 
                     nullable=False)
    type = relation(Type, backref='entities')
    value = Column(Text, nullable=False)

我想查询一个实体中曾经使用过的所有类型。在纯 SQL 中,我将通过以下方式完成此操作:

SELECT entity_types.*
FROM entities
    JOIN entity_types ON entities.type == entity_types.type
GROUP BY entity_types.type

如何使用 SqlAlchemy 的 ORM-Engine 解决这个问题?

我已经尝试了这些查询,但它们都没有返回我想要的:

session.query(Action.type).group_by(Action.type).all()

session.query(Type).select_from(Action).group_by(Type).all()

我也尝试过使用options(joinedload('type')),但我发现这仅用于强制急切加载并绕过延迟加载。

补充:我刚刚在Entityrelation 中添加了backref。我认为这个问题可以通过查询count(Type.entities) > 0 来解决,但是我无法弄清楚如何准确地形成一个有效的 ORM 查询。

【问题讨论】:

    标签: python sql sqlalchemy


    【解决方案1】:

    我刚刚想通了:

    session.query(ActionType).filter(ActionType.actions.any()).all()
    

    any() 可以解决问题。

    【讨论】:

      猜你喜欢
      • 2021-08-01
      • 1970-01-01
      • 2022-08-24
      • 1970-01-01
      • 1970-01-01
      • 2012-10-06
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多