db = SQLAlchemy(app)
# relationship: 增加了关系引用,为了查询方便. 由原先的2次查询, 改为了1次查询
# 一个角色对应多个用户:一的一方(Role)定义关系引用和反向引用. 多的一方(User)定义外键
# users 是为了当前模型方便查询定义的. backref='role', 这里的role是给关联模型提供的查询属性
class Role(db.Model):
__tablename__ = 't_roles'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64), unique=True)
users = db.relationship('User', backref='role')
class User(db.Model):
__tablename__ = 't_users'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64), unique=True)
role_id = db.Column(db.Integer, db.ForeignKey('t_roles.id'))
db.create_all()
role1 = Role(name='admin')
role2 = Role(name='user')
db.session.add_all([role1, role2])
db.session.commit()
user1 = User(name='zs', role_id=role1.id)
user2 = User(name='ls', role_id=role2.id)
user3 = User(name='ww', role_id=role1.id)
db.session.add_all([user1, user2, user3])
db.session.commit()
# ipython或ipython3环境里面运行
# 关系引用和反向引用查询
In [1]: from Flask_sqlalchemy import *
In [2]: user = User.query.get(1)
In [3]: user.role.name
Out[3]: 'admin'
In [4]: role = Role.query.get(1)
In [5]: role.users
Out[5]: [<User 1>, <User 3>]