如何使用协会表,in子句和子查询查询sqlalchemy?
我有一个课程表和一张学生表定义为
class Course(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(200))
tutor = db.Column(db.Integer, db.ForeignKey("tutor.id"))
students = db.relationship("Student", secondary=association_table)
class Student(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50))
email = db.Column(db.String(50))
courses = db.relationship("Course", secondary=association_table)
与他们之间的许多关系,我创建了一个相关的表,
association_table = db.Table(
"association",
db.Model.metadata,
db.Column("course_id", db.ForeignKey("course.id")),
db.Column("student_id", db.ForeignKey("student.id")))
我想查询并获得特定学生所学的所有课程的结果。 SQL查询就像
SELECT * FROM course WHERE course.id IN (SELECT course_id FROM association WHERE student_id = 2)
我该如何使用SQLalchemy这样做?
目前,我的众多失败尝试的尝试之一是
query_ = self.session.query(Course)
query2 = self.session.query(association_table.course_id).all().filter_by(student_id=view_kwargs.get('student_id'))
query_ = query_.filter(Course.id.in_(query2)).all()
,当我使用Postman的API调用它时,我会得到这个。
AttributeError: 'Table' object has no attribute 'course_id'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
带有子选项的子句中的
不是最优雅的(至少在过去,也不是执行查询的最佳方法)。
为了使用
JOIN
具有绝对相同结果的子句,请尝试下面的查询,这很简洁:并将产生以下
sql
:但是,避免在
student 表格,以下更明确的查询将产生相同的结果:
这将导致
sql
与以下相似:The
IN
clause with sub-select is not the most elegant (and at least in the past, also not the most optimal way to execute the query).In order to use
JOIN
clause with absolutely the same result please try the query below which is very succinct:and will produce following
SQL
:However, to avoid joining on the
student
table alltogether, the below more explicit query will result in the same outcome:which will result in the
SQL
similar to below:更新:我找到了一个可行的解决方案,实际上很简单。
就像:
Update: I have found a solution that works and which is quite simple actually.
It goes like: