Domanda

I'm creating a record system, where a student can be enrolled into a class.

# 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")

I want to display all of the students that are not yet enrolled in a class, so I've used the following code in my program and template, but it just displays all of the students on the page.

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
È stato utile?

Soluzione

I think your code even outputs each student name as many times as there are students in the current class (minus one if the student is enrolled in the class) :)

Your current logic is

for student in all_student:  # Alice, Bob, Claude
    for enrolled_student in current_class.enrolled_students: # Alice, Bob
        if student != enrolled_student:
            print student

The output of the above would be

Alice, Alice, Bob, Bob, Claude, Claude, Claude  

(first iteration: Alice == Alice, skip. Second: Alice != Bob, print. Third: Alice != Claude, print, etc.)

Also your relationship setup is not quite "idiomatic sqlalchemy". Have a look at http://docs.sqlalchemy.org/en/rel_0_9/orm/relationships.html#many-to-many If you set up your models as in the example (e.q. using the secondary parameter of the relationship() function), you'll be able to do something like

% 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

Altri suggerimenti

Your query is all wrong..

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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top