例如,我有2个模特:一个是学生,另一个是老师
我是否必须在构造函数self.teacher_id = teacher_id
中添加到Student?
class Student(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Text)
age = db.Column(db.Integer)
teacher_id = db.Column(db.Integer, db.ForeignKey('teacher.id'))
def __init__(self, name, age):
self.name = name
self.age = age
class Teacher(db.Model):
id = db.Column(db.Integer, primary_key=True)
subject = db.Column(db.Text)
students = db.relationship('Student', backref='person', lazy='dynamic')
def __init__(self, subject):
self.subject = subject
答案 0 :(得分:0)
由于一个学生有很多老师,一个老师有很多学生,因此它是一个多对多的关系,你需要添加一个关联表来做到这一点:
class Student(db.Model):
__tablename__ = 'student'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Text)
age = db.Column(db.Integer)
teachers = db.relationship('Teacher', secondary='xtable', backref=db.backref('students', lazy='dynamic'))
class Teacher(db.Model):
__tablename__ = 'teacher'
id = db.Column(db.Integer, primary_key=True)
subject = db.Column(db.Text)
class Xtable(db.Model):
__tablename__ = 'xtable'
student_id = db.Column('student_id', db.ForeignKey('student.id'))
teacher_id = db.Column('teacher_id', db.ForeignKey('teacher.id'))
现在您应该可以查询Student.teachers
和Teacher.students
文档:http://docs.sqlalchemy.org/en/latest/orm/basic_relationships.html#many-to-many
*请注意,当使用backref参数而不是relationship.back_populates时,backref将自动使用相同的辅助参数作为反向关系。 因此,您不必将关系语句放在两个类中