我正在创建一个记录系统,学生可以在这里注册课程。
# MODEL
class Association(Base):
__tablename__ = 'association'
class_id = Column(Integer, ForeignKey('classes.id'), primary_key=True)
student_id = Column(Integer, ForeignKey('students.id'), primary_key=True)
theClass = relationship("Class")
class Student(Base):
__tablename__ = 'students'
id = Column(Integer, primary_key=True)
name = Column(String(30))
classlist = relationship("Association", backref='student')
class Class(Base):
__tablename__ = 'classes'
id = Column(Integer, primary_key=True)
name = Column(String(20), nullable=False)
teacher_id = Column(Integer, ForeignKey('teachers.id'))
enrolled_students = relationship("Association")
我想显示所有尚未注册课程的学生,所以我在我的课程和模板中使用了以下代码,但它只显示了页面上的所有学生。
currentClass = session.query(Class).filter_by(id=class_id).first()
students = session.query(Student).all()
# TEMPLATE
% for st in students:
% for assoc in currentClass.enrolled_students:
% if st.id != assoc.student_id:
<input type="checkbox" name="student_id" value="${ st.id }" >${ st.id } - ${ st.forename } ${ st.surname }</input><br/>
% endif
% endfor
% endfor
答案 0 :(得分:2)
我认为你的代码甚至输出每个学生姓名的次数与当前班级的学生一样多(如果学生在课堂上注册,则减1):)
您当前的逻辑是
for student in all_student: # Alice, Bob, Claude
for enrolled_student in current_class.enrolled_students: # Alice, Bob
if student != enrolled_student:
print student
以上的输出将是
Alice, Alice, Bob, Bob, Claude, Claude, Claude
(第一次迭代:Alice == Alice,跳过。第二次:Alice!= Bob,打印。第三次:Alice:Alice!= Claude,print等)
此外,您的关系设置并不完全&#34;惯用的sqlalchemy&#34;。看一下http://docs.sqlalchemy.org/en/rel_0_9/orm/relationships.html#many-to-many如果您按照示例(使用secondary
函数的relationship()
参数的eq)设置模型,您将能够执行类似的操作
% for st in students:
% if st not in class.enrolled_students:
<input type="checkbox" name="student_id" value="${ st.id }" >${ st.id } - ${ st.forename } ${ st.surname }</input><br/>
% endif
% endfor
答案 1 :(得分:0)
你的查询都错了..
students = Session.query(Student).\
filter(Student.classlist == None).all()
for student ins students:
<input type="checkbox" name="student_id" value="${ st.id }" >${ st.id } - ${ st.forename } ${ st.surname }</input><br/>
endfor