如何加入sqlachemy?
class Enrollments(Base):
__tablename__ = 'Enrollments'
StudentID = Column(INTEGER, ForeignKey('Student.StudentID'))
FinalGrade = Column(VARCHAR(3))
class Student(Base):
__tablename__ = 'Student'
StudentID = Column(INTEGER, primary_key=True)
Name = Column(VARCHAR(100))
EnrolledIn = relationship('Enrollments')
session.query(Student).join(Enrollments).all() #what isn't giving me what I expect
我希望这能给我三个栏目(StudentID,Name,FinalGrade,EnrolledIn),但是它只给了我没有应该附加的注册的学生对象,我做错了什么?
答案 0 :(得分:2)
注册将附加到每个Student
对象,student.EnrolledIn
。
但加入是为了查询,而不是提取;如果你想加载它们,你想要
session.query(Student).options(joinedload(Student.EnrolledIn))
此处记录了关系加载:http://docs.sqlalchemy.org/en/rel_0_9/orm/tutorial.html#eager-loading
顺便说一下,您可能希望将snake_case
用于对象的属性;由于DromedaryCase
通常仅为类名保留,因此阅读有点令人困惑:)