嵌套的一对多关系 sqlalchemy 过滤
Posted
技术标签:
【中文标题】嵌套的一对多关系 sqlalchemy 过滤【英文标题】:Nested one-to-many relationship sqlalchemy filtering 【发布时间】:2021-12-17 14:58:34 【问题描述】:我试图在 sqlalchemy 中过滤嵌套的一对多关系,但它只在内部连接(第二个)中提供过滤器,我如何在外部连接而不是内部连接中指定过滤器?
我有
-
一对多学校 -->课程
一对多班级 -> 学生
我试图让特定学校、特定班级的所有学生
模型.py
class School(Base):
__tablename__ = 'schools'
id = Column(Integer, primary_key=True)
name = Column(String)
# # Relationship for one-many - parent of classes
classes = relationship("Class")
def __repr__(self):
return "<School(name='%s')>" % self.name
class Class(Base):
__tablename__ = 'classes'
id = Column(Integer, primary_key=True)
name = Column(String)
# foreign Key for the parent - child of school
school_id = Column(Integer, ForeignKey('schools.id'))
# Relationship for one-many - parent of students
students = relationship("Student")
def __repr__(self):
return "<Class(name='%s')>" % self.name
class Student(Base):
__tablename__ = 'students'
id = Column(Integer, primary_key=True)
name = Column(String)
fullname = Column(String)
nickname = Column(String)
# foreign Key for the parent - child of school
class_id = Column(Integer, ForeignKey('classes.id'))
def __repr__(self):
return "<Student(name='%s', fullname='%s', nickname='%s')>" % (
self.name, self.fullname, self.nickname)
查询是
info = session.query(SchoolModel). \
options(subqueryload(SchoolModel.classes).subqueryload(ClassModel.students)). \
filter(SchoolModel.id == parent_lookup_class__student). \
filter(ClassModel.id == parent_lookup_class). \
filter(StudentModel.id == pk). \
first()
输出为所有学生提供与其相关的所有信息,我的查询有什么问题?
【问题讨论】:
【参考方案1】:问题是我正在使用subqueryload
,它实际上无法修改,而是我使用contains_eager()
过滤我的结果
新查询是
info = session.query(SchoolModel). \
join(SchoolModel.classes). \
join(ClassModel.students). \
options(contains_eager(SchoolModel.classes), contains_eager(SchoolModel.classes, ClassModel.students)). \
filter(SchoolModel.id == parent_lookup_class__student). \
filter(ClassModel.id == parent_lookup_class). \
filter(StudentModel.id == pk). \
populate_existing(). \
first()
【讨论】:
以上是关于嵌套的一对多关系 sqlalchemy 过滤的主要内容,如果未能解决你的问题,请参考以下文章