我正在使用Flask应用程序,其中我有一个LargeGroupAttendance模型,该模型引用另一个名为Attendee的模型。我正在尝试请求所有符合特定条件的LargeGroupAttendance对象,但我试图通过参加者模型的列对它们进行排序 - 这是否可能?以下是两种型号:
""" Attendeee Class """
class Attendee(Base):
__tablename__ = 'attendee'
id = Column(Integer, primary_key=True)
first_name = Column(String(200))
last_name = Column(String(200))
year = Column(String(200))
email = Column(String(100), unique=True)
dorm = Column(String(100))
def __init__(self, first_name, last_name, year, email, dorm):
self.first_name = first_name
self.last_name = last_name
self.year = year
self.email = email
self.dorm = dorm
def __repr__(self):
return '<Attendee %r>' % self.first_name
""" Large Group Attendance Class """
class LargeGroupAttendance(Base):
__tablename__ = 'large_group_attendance'
id = Column(Integer, primary_key=True)
first_time = Column(Integer)
large_group_id = Column(Integer, ForeignKey('large_group.id'))
large_group = relationship("LargeGroup", backref=backref('large_group_attendance', order_by=id))
attendee_id = Column(Integer, ForeignKey('attendee.id'))
attendee = relationship("Attendee", backref=backref('large_group_attendance', order_by=id))
我是否需要在我的与会者课程中添加一些内容才能实现这一目标?这是我之前尝试过的一个查询,但它没有输出(也没有错误......)。我哪里错了?
attendance_records = db.session.query(LargeGroupAttendance).filter_by(large_group_id=event_id).order_by(desc(LargeGroupAttendance.attendee.first_name))
答案 0 :(得分:8)
我认为您需要在查询中添加联接,如下所示:
.join(LargeGroupAttendance.attendee)
以便最终查询如下所示:
attendance_records = (db.session.query(LargeGroupAttendance).
filter_by(large_group_id = event_id).
join(Attendee, LargeGroupAttendance.attendee).
order_by(desc(Attendee.first_name))
)
有关更详细的说明,请参阅SQLAlchemy: How to order query results (order_by) on a relationship's field?