1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
| 多对多比较复杂,有两种情况,需要新建一个表来进行映射,这里我们采用学生和老师的关系来理解第一种情况,即多对多是两个不同的类 1. 一个学生的类,肯定是对应着多位老师的类 2. 一个老师的类,肯定也是对应着多位学生的类 association = db.Table('association', db.Column('student_id',db.Integer,db.ForeignKey('student.id')), db.Column('teacher_id',db.Integer,db.ForeignKey('teacher.id')), )
class Student(db.Model): __tablename__ ='student' id = db.Column(db.Integer,primary_key=True) name=db.Column(db.String(64)) teachers = db.relationship('Teacher',secondary=association,backref='students')
class Teacher(db.Model): __tablename__ ='teacher' id =db.Column(db.Integer,primary_key=True) name = db.Column(db.String(120)) students = db.relationship('Student',secondary=association,backref='teachers')
>>> s = Student(name="johnw1") >>> s2 = Student(name="jacob") >>> t1 = Teacher(name="jack1") >>> t2 = Teacher(name="jack2")
>>> s.teachers.append(t1) >>> s.teachers.append(t2) >>> s2.teachers.append(t1) >>> s2.teachers.append(t2)
>>> db.session.add(s) >>> db.session.add(t1) >>> db.session.add(t2) >>> db.session.add(s2) >>> db.session.commit()
>>> s2.teachers [<Teacher 3>, <Teacher 4>] >>> s2.teachers[0].student [<Student 2>, <Student 3>] >>> s.teachers [<Teacher 3>, <Teacher 4>]
>>> s.teachers[0].students [<Student 2>, <Student 3>]
>>> s3 = Student(name="wen") >>> s4 = Student(name="wen2") >>> t1.students.append(s3) >>> t1.students.append(s4) >>> db.session.commit()
第二种情况,多对多是同一个类。以本程序为例子,用户关注和被关注,都是用到了user这个类而已。 1. 首先新建一个映射的表 follow_table = db.Table("follow_table", db.Column("follower_id",db.Integer,db.ForeignKey('user.id')), db.Column("followed_id",db.Integer,db.ForeignKey("user.id")))
在这里我们将关注者放在了左边,被关注者放在了右边
2. 创建关系 class User(UserMixin,db.Model): followed = db.relationship("User",secondary=follow_table, primaryjoin = (follow_table.c.follower_id == id), secondaryjoin = (follow_table.c.followed_id == id), backref = db.backref('followers',lazy='dynamic'),lazy='dynamic'))
通过sql打印,我们可以看到 >>> print(u2.followed) SELECT user.id AS user_id, user.username AS user_username, user.email AS user_email, user.password_hash AS user_password_hash, user.des AS user_des, user.register_date AS user_register_date FROM user, follow_table WHERE follow_table.follower_id = %(param_1)s AND follow_table.followed_id = user.id
|