flask中一对一,一对多以及多对多关系的设定
一对多关系:
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'