SqlAlchemy - 查询关系属性是一个列表

SqlAlchemy - make a query where Relationship Attribute is a list

我有两个模型:

class Profile(Base):
    __tablename__ = 'profiles'

    id = Column(Integer, primary_key=True)
    ...

    stagesP_list = relationship(
        'StageP', 
        back_populates='profiles_list',
        secondary=stageP_profile
        )


class Project(Base):
    __tablename__ = 'projects'

    id = Column(Integer, primary_key=True)
    ...

    stagesP_list = relationship(
        'StageP', 
        back_populates='projects_list',
        secondary=stageP_project
        )

我需要 select 配置文件,其中 Profile.stagesP_list 的至少一个值包含在 project.stagesP_list 中。

请帮助撰写查询或指明搜索方向。

如果您加载了 project 个实例,您可以编写以下查询:

project = ...
stageP_ids = [obj.id for obj in project.stagesP_list]

query = session.query(Profile).filter(
    Profile.stagesP_list.any(StageP.id.in_(stageP_ids))
)

您也可以直接在数据库上执行连接,只需要 project_id:

query = (
    session.query(Profile)
    .join(StageP, Profile.stagesP_list)
    .join(Project, StageP.projects_list)
    .where(Project.id == project_id)
    .distinct()
)