多对多的定义可以使用关联表,或者重新定义一个模型,通过模型定义多对多的自引用在flask web开发书里有讲到,这里主要演示用关联表定义的方法。
from flask_sqlalchemy import SQLAlchemy from flask import Flask app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db' db = SQLAlchemy(app) follows=db.Table('follows', db.Column('follower_id',db.Integer,db.ForeignKey('users.id')), db.Column('followed_id',db.Integer,db.ForeignKey('users.id'))) class User(db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(64), unique=True, index=True) followers=db.relationship('User', secondary=follows, primaryjoin=id==follows.c.followed_id, secondaryjoin=id==follows.c.follower_id, backref=db.backref('followed',lazy='dynamic'), lazy='dynamic') u1,u2=User(username='u1'),User(username='u2') u1.followed.append(u2) print "u1 following :",u1.followed[0].username print "u2 followers :",u2.followers[0].username
表中定义了关注的人,和粉丝两个字段。主要需要设置primaryjoin跟secondaryjoin参数