简体   繁体   中英

How do I set a foreign key in the constructor of a SQLAlchemy (Python, Flask) db model?

For example, I have 2 models:, one of a student and one of a teacher.
Do I have to add to Student in the constructor self.teacher_id = teacher_id ?

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

Since one student has many teachers and one teacher has many students, its a many-to-many relationship and you need to add an association table to do that:

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'))

And now you should be able to query Student.teachers and Teacher.students

Docs: http://docs.sqlalchemy.org/en/latest/orm/basic_relationships.html#many-to-many

*Note that when using the backref parameter instead of relationship.back_populates, the backref will automatically use the same secondary argument for the reverse relationship. So you don't have to put the relationship statement in both classes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM