SQLAlchemy操作
1 新增
user = User(mobile='15612345678', name='itcast') db.session.add(user) db.session.commit() profile = Profile(id=user.id) db.session.add(profile) db.session.commit()
对于批量添加也可使用如下语法
db.session.add_all([user1, user2, user3])
db.session.commit()
2 查询
all()
查询所有,返回列表
User.query.all()
first()
查询第一个,返回对象
User.query.first()
get()
根据主键ID获取对象,若主键不存在返回None
User.query.get(2)
另一种查询方式
db.session.query(User).all()
db.session.query(User).first()
db.session.query(User).get(2)
filter_by
进行过虑
User.query.filter_by(mobile='13911111111').first() User.query.filter_by(mobile='13911111111', id=1).first() # and关系
filter
进行过虑
User.query.filter(User.mobile=='13911111111').first()
逻辑或
from sqlalchemy import or_ User.query.filter(or_(User.mobile=='13911111111', User.name.endswith('号'))).all()
逻辑与
from sqlalchemy import and_ User.query.filter(and_(User.name != '13911111111', User.mobile.startswith('185'))).all()
逻辑非
from sqlalchemy import not_ User.query.filter(not_(User.mobile == '13911111111')).all()
offset
偏移,起始位置
User.query.offset(2).all()
limit
获取限制数据
User.query.limit(3).all()
order_by
排序
User.query.order_by(User.id).all() # 正序 User.query.order_by(User.id.desc()).all() # 倒序
复合查询
User.query.filter(User.name.startswith('13')).order_by(User.id.desc()).offset(2).limit(5).all() # 或者: query = User.query.filter(User.name.startswith('13')) query = query.order_by(User.id.desc()) query = query.offset(2).limit(5) ret = query.all()
优化查询
user = User.query.filter_by(id=1).first() # 查询所有字段 select user_id, mobile...... select * from # 程序不要使用 select user_id, mobile,.... # 查询指定字段 from sqlalchemy.orm import load_only User.query.options(load_only(User.name, User.mobile)).filter_by(id=1).first() # 查询特定字段
聚合查询
from sqlalchemy import func db.session.query(Relation.user_id, func.count(Relation.target_user_id)).filter(Relation.relation == Relation.RELATION.FOLLOW).group_by(Relation.user_id).all()
关联查询
1. 使用ForeignKey
class User(db.Model): ... profile = db.relationship('UserProfile', uselist=False) followings = db.relationship('Relation') class UserProfile(db.Model): id = db.Column('user_id', db.Integer, db.ForeignKey('user_basic.user_id'), primary_key=True, doc='用户ID') ... class Relation(db.Model): user_id = db.Column(db.Integer, db.ForeignKey('user_basic.user_id'), doc='用户ID') ... # 测试 user = User.query.get(1) user.profile.gender user.followings
from datetime import datetime from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) # app.config.from_envvar('PROJECT_SETTING') app.config.from_pyfile('settings.py') db = SQLAlchemy(app) class User(db.Model): """ 用户基本信息 """ __tablename__ = 'user_basic' class STATUS: ENABLE = 1 DISABLE = 0 id = db.Column('user_id', db.Integer, primary_key=True, doc='用户ID') mobile = db.Column(db.String, doc='手机号') password = db.Column(db.String, doc='密码') name = db.Column('user_name', db.String, doc='昵称') profile_photo = db.Column(db.String, doc='头像') last_login = db.Column(db.DateTime, doc='最后登录时间') is_media = db.Column(db.Boolean, default=False, doc='是否是自媒体') is_verified = db.Column(db.Boolean, default=False, doc='是否实名认证') introduction = db.Column(db.String, doc='简介') certificate = db.Column(db.String, doc='认证') article_count = db.Column(db.Integer, default=0, doc='发帖数') following_count = db.Column(db.Integer, default=0, doc='关注的人数') fans_count = db.Column(db.Integer, default=0, doc='被关注的人数(粉丝数)') like_count = db.Column(db.Integer, default=0, doc='累计点赞人数') read_count = db.Column(db.Integer, default=0, doc='累计阅读人数') account = db.Column(db.String, doc='账号') email = db.Column(db.String, doc='邮箱') status = db.Column(db.Integer, default=1, doc='状态,是否可用') # Foreignkey关联查询 profile = db.relationship('UserProfile', uselist=False) followings = db.relationship('Relation') class UserProfile(db.Model): """ 用户资料表 """ __tablename__ = 'user_profile' class GENDER: MALE = 0 FEMALE = 1 id = db.Column('user_id', db.Integer, db.ForeignKey('user_basic.user_id'), primary_key=True, doc='用户ID') # id = db.Column('user_id', db.Integer, primary_key=True, doc='用户ID') gender = db.Column(db.Integer, default=0, doc='性别') birthday = db.Column(db.Date, doc='生日') real_name = db.Column(db.String, doc='真实姓名') id_number = db.Column(db.String, doc='身份证号') id_card_front = db.Column(db.String, doc='身份证正面') id_card_back = db.Column(db.String, doc='身份证背面') id_card_handheld = db.Column(db.String, doc='手持身份证') ctime = db.Column('create_time', db.DateTime, default=datetime.now, doc='创建时间') utime = db.Column('update_time', db.DateTime, default=datetime.now, onupdate=datetime.now, doc='更新时间') register_media_time = db.Column(db.DateTime, doc='注册自媒体时间') area = db.Column(db.String, doc='地区') company = db.Column(db.String, doc='公司') career = db.Column(db.String, doc='职业') class Relation(db.Model): """ 用户关系表 """ __tablename__ = 'user_relation' class RELATION: DELETE = 0 FOLLOW = 1 BLACKLIST = 2 id = db.Column('relation_id', db.Integer, primary_key=True, doc='主键ID') user_id = db.Column(db.Integer, db.ForeignKey('user_basic.user_id'), doc='用户ID') # user_id = db.Column(db.Integer, doc='用户ID') target_user_id = db.Column(db.Integer, doc='目标用户ID') relation = db.Column(db.Integer, doc='关系') ctime = db.Column('create_time', db.DateTime, default=datetime.now, doc='创建时间') utime = db.Column('update_time', db.DateTime, default=datetime.now, onupdate=datetime.now, doc='更新时间') target_user = db.relationship('User', primaryjoin='Relation.target_user_id==foreign(User.id)', uselist=False)
2. 使用primaryjoin
class User(db.Model): ... profile = db.relationship('UserProfile', primaryjoin='User.id==foreign(UserProfile.id)', uselist=False) followings = db.relationship('Relation', primaryjoin='User.id==foreign(Relation.user_id)') # 测试 user = User.query.get(1) user.profile.gender user.followings
from datetime import datetime from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) # app.config.from_envvar('PROJECT_SETTING') app.config.from_pyfile('settings.py') db = SQLAlchemy(app) class User(db.Model): """ 用户基本信息 """ __tablename__ = 'user_basic' class STATUS: ENABLE = 1 DISABLE = 0 id = db.Column('user_id', db.Integer, primary_key=True, doc='用户ID') mobile = db.Column(db.String, doc='手机号') password = db.Column(db.String, doc='密码') name = db.Column('user_name', db.String, doc='昵称') profile_photo = db.Column(db.String, doc='头像') last_login = db.Column(db.DateTime, doc='最后登录时间') is_media = db.Column(db.Boolean, default=False, doc='是否是自媒体') is_verified = db.Column(db.Boolean, default=False, doc='是否实名认证') introduction = db.Column(db.String, doc='简介') certificate = db.Column(db.String, doc='认证') article_count = db.Column(db.Integer, default=0, doc='发帖数') following_count = db.Column(db.Integer, default=0, doc='关注的人数') fans_count = db.Column(db.Integer, default=0, doc='被关注的人数(粉丝数)') like_count = db.Column(db.Integer, default=0, doc='累计点赞人数') read_count = db.Column(db.Integer, default=0, doc='累计阅读人数') account = db.Column(db.String, doc='账号') email = db.Column(db.String, doc='邮箱') status = db.Column(db.Integer, default=1, doc='状态,是否可用') # primaryjoin关联查询 profile = db.relationship('UserProfile', primaryjoin='User.id==foreign(UserProfile.id)', uselist=False) followings = db.relationship('Relation', primaryjoin='User.id==foreign(Relation.user_id)') class UserProfile(db.Model): """ 用户资料表 """ __tablename__ = 'user_profile' class GENDER: MALE = 0 FEMALE = 1 id = db.Column('user_id', db.Integer, primary_key=True, doc='用户ID') gender = db.Column(db.Integer, default=0, doc='性别') birthday = db.Column(db.Date, doc='生日') real_name = db.Column(db.String, doc='真实姓名') id_number = db.Column(db.String, doc='身份证号') id_card_front = db.Column(db.String, doc='身份证正面') id_card_back = db.Column(db.String, doc='身份证背面') id_card_handheld = db.Column(db.String, doc='手持身份证') ctime = db.Column('create_time', db.DateTime, default=datetime.now, doc='创建时间') utime = db.Column('update_time', db.DateTime, default=datetime.now, onupdate=datetime.now, doc='更新时间') register_media_time = db.Column(db.DateTime, doc='注册自媒体时间') area = db.Column(db.String, doc='地区') company = db.Column(db.String, doc='公司') career = db.Column(db.String, doc='职业') class Relation(db.Model): """ 用户关系表 """ __tablename__ = 'user_relation' class RELATION: DELETE = 0 FOLLOW = 1 BLACKLIST = 2 id = db.Column('relation_id', db.Integer, primary_key=True, doc='主键ID') user_id = db.Column(db.Integer, doc='用户ID') target_user_id = db.Column(db.Integer, doc='目标用户ID') relation = db.Column(db.Integer, doc='关系') ctime = db.Column('create_time', db.DateTime, default=datetime.now, doc='创建时间') utime = db.Column('update_time', db.DateTime, default=datetime.now, onupdate=datetime.now, doc='更新时间') target_user = db.relationship('User', primaryjoin='Relation.target_user_id==foreign(User.id)', uselist=False)
3. 指定字段关联查询
class Relation(db.Model): ... target_user = db.relationship('User', primaryjoin='Relation.target_user_id==foreign(User.id)', uselist=False) from sqlalchemy.orm import load_only, contains_eager Relation.query.join(Relation.target_user).options(load_only(Relation.target_user_id), contains_eager(Relation.target_user).load_only(User.name)).all()
3 更新
-
方式一
user = User.query.get(1) user.name = 'Python' db.session.add(user) db.session.commit()
-
方式二
User.query.filter_by(id=1).update({'name':'python'}) db.session.commit()
4 删除
-
方式一
user = User.query.order_by(User.id.desc()).first() db.session.delete(user) db.session.commit()
-
方式二
User.query.filter(User.mobile=='18512345678').delete() db.session.commit()
5 事务
environ = {'wsgi.version':(1,0), 'wsgi.input': '', 'REQUEST_METHOD': 'GET', 'PATH_INFO': '/', 'SERVER_NAME': 'itcast server', 'wsgi.url_scheme': 'http', 'SERVER_PORT': '80'} with app.request_context(environ): try: user = User(mobile='18911111111', name='itheima') db.session.add(user) db.session.flush() # 将db.session记录的sql传到数据库中执行 profile = UserProfile(id=user.id) db.session.add(profile) db.session.commit() except: db.session.rollback()
壬戌之秋,七月既望,苏子与客泛舟游于赤壁之下。清风徐来,水波不兴。举酒属客,诵明月之诗,歌窈窕之章。少焉,月出于东山之上,徘徊于斗牛之间。白露横江,水光接天。纵一苇之所如,凌万顷之茫然。浩浩乎如冯虚御风,而不知其所止;飘飘乎如遗世独立,羽化而登仙。
于是饮酒乐甚,扣舷而歌之。歌曰:“桂棹兮兰桨,击空明兮溯流光。渺渺兮予怀,望美人兮天一方。”客有吹洞箫者,倚歌而和之。其声呜呜然,如怨如慕,如泣如诉,余音袅袅,不绝如缕。舞幽壑之潜蛟,泣孤舟之嫠妇。
苏子愀然,正襟危坐而问客曰:“何为其然也?”客曰:“月明星稀,乌鹊南飞,此非曹孟德之诗乎?西望夏口,东望武昌,山川相缪,郁乎苍苍,此非孟德之困于周郎者乎?方其破荆州,下江陵,顺流而东也,舳舻千里,旌旗蔽空,酾酒临江,横槊赋诗,固一世之雄也,而今安在哉?况吾与子渔樵于江渚之上,侣鱼虾而友麋鹿,驾一叶之扁舟,举匏樽以相属。寄蜉蝣于天地,渺沧海之一粟。哀吾生之须臾,羡长江之无穷。挟飞仙以遨游,抱明月而长终。知不可乎骤得,托遗响于悲风。”
苏子曰:“客亦知夫水与月乎?逝者如斯,而未尝往也;盈虚者如彼,而卒莫消长也。盖将自其变者而观之,则天地曾不能以一瞬;自其不变者而观之,则物与我皆无尽也,而又何羡乎!且夫天地之间,物各有主,苟非吾之所有,虽一毫而莫取。惟江上之清风,与山间之明月,耳得之而为声,目遇之而成色,取之无禁,用之不竭,是造物者之无尽藏也,而吾与子之所共适。”
客喜而笑,洗盏更酌。肴核既尽,杯盘狼籍。相与枕藉乎舟中,不知东方之既白。