flask-SQLAlchemy 直接使用了SQLAlchemy,只不过是把SQLAlchemy的功能减少了很大一部分,只支持其中很少的一部分功能,因此,在使用falsk-SQLAlchemy,可以结合SQLAlchemy中的功能一起使用。
这里主要讲两个数据库之间关联关系的创建,以及之间在这种关系之下的 add、查询等操作
1、建立关联关系
class Role(db.Model):
__tablename__ = 'roles'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64), unique=True)
users = db.relationship('User', backref='role')
def __repr__(self):
return "<Role %r>"%self.name
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), unique=True)
role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))
def __repe__(self):
return "<User %r>"%self.username
其中 User中的,role_id = db.Column(db.Integer, db.ForeignKey(‘roles.id’)), 表示是外键 和 Role表中的id 相关联
Role表中的 users = db.relationship(‘User’, backref=’role’) 表示 从Role表 到 User表的连接(一个反向的连接关系)
2、插入
admin_role = Role(name='Admin')
mod_role = Role(name='Moderator')
user_role = Role(name='User')
user_john = User(username='john', role=admin_role)
user_susan = User(username='susan', role=user_role)
user_david = User(username='david', role=user_role)
db.session.add(admin_role)
db.session.add(mod_role)
db.session.add(user_role)
db.session.add(user_john)
db.session.add(user_susan)
db.session.add(user_david)
db.session.commit()
3、查询
admin_role = Role.get(id)
admin_user = admin_role.role.filter(.....).all()
在两个表之间有了关联之后,我们可以直接通过之间的关联关系或者另一个表的查询结果
4、filter 和 filter_by的区别
filter_by 是一种简单的查询操作
data = Role.query.filter_by(id=123).all()
filter是一种更精确的查询,在这里面可以做很多复杂的操作,比如运用sql中的函数(in、add、or…..)
data = Role.query.filter_by(and_(Role.id == xxx, Role.name == xxx))