如何使用SQLAlchemy进行嵌套查询?

时间:2017-07-23 23:42:08

标签: python sqlalchemy

schedule_association_table = Table(
    'schedule_association', Base.metadata,
    Column('course_id', Integer, ForeignKey('course.idx')),
    Column('schedule_id', Integer, ForeignKey('schedule.idx')),
)
class Schedule(Base):
    __tablename__ = "schedule"
    idx = Column(Integer, primary_key=True)
    start_time = Column(Time())
    end_time = Column(Time())

class Course(Base):
    __tablename__ = 'course'
    idx = Column(Integer, primary_key=True)
    course_id = Column(String(16))
    schedules = relationship("Schedule", backref="courses", secondary=schedule_association_table)

在这个模型中,我想查询start_time和end_time之间的过程。我可以通过以下方式查询,但这不是一个好的解决方案。还有其他更好的方法吗?

def get_course_between_time(start_time, end_time):
    result = []
    for course in db.session(Course).all():
        for schedule in course.schedules:
            if start_time < schedule.start_time and end_time > schedule.end_time:
                result.append(course)
                break
    return result

1 个答案:

答案 0 :(得分:1)

您可以use EXISTS查询具有符合条件的相关时间表的课程:

def get_course_between_time(start_time, end_time):
    courses = db.session.query(Course).\
        filter(Course.schedules.any((Schedule.start_time > start_time) &
                                    (Schedule.end_time < end_time))).\
        all()

    return courses