flask中一對一,一對多以及多對多關係的設定
阿新 • • 發佈:2018-11-11
一對多關係:
class Grade(db.Model): id=db.Column(db.Integer,primary_key=True) name=db.Column(db.String(20),nullable=False) num = db.Column(db.Integer, default=0) time = db.Column(db.String(20), default='2018-01-01') students=db.relationship('Student',backref='gd',lazy='dynamic') __tablename__='grade' class Student(db.Model): id=db.Column(db.String(50),primary_key=True) name=db.Column(db.String(50),nullable=False) password = db.Column(db.String(50), nullable=False) sex = db.Column(db.String(50), nullable=False) phone = db.Column(db.String(11), nullable=False) photo= db.Column(db.String(100), default=None) grades=db.Column(db.Integer,db.ForeignKey('grade.id')) __tablename__ = 'student'
一對一關係:在relationship裡面lazy變數去掉,換成uselist=False
多對多關係:
其實多對多關係的處理是在兩個表之間建立另外一張表格,設定兩個外來鍵去分別關聯另外兩張表的主鍵
t_g=db.Table('t_g',db.Column('t_id',db.String(50),db.ForeignKey('teacher.id')),db.Column('g_id',db.Integer,db.ForeignKey('grade.id'))) class Teacher(db.Model,DBO): id=db.Column(db.String(50),primary_key=True) name=db.Column(db.String(50),nullable=False) password = db.Column(db.String(50), nullable=False) phone=db.Column(db.String(11), nullable=False) photo=db.Column(db.String(100),default=None) grades=db.relationship('Grade',secondary=t_g,backref='th',lazy='dynamic') __tablename__='teacher' class Grade(db.Model,DBO): id=db.Column(db.Integer,primary_key=True) name=db.Column(db.String(20),nullable=False) num = db.Column(db.Integer, default=0) time = db.Column(db.String(20), default='2018-01-01') students=db.relationship('Student',backref='gd',lazy='dynamic') __tablename__='grade'