当前位置:网站首页>【Flask】Flask-SQLAlchemy的增删改查(CRUD)操作
【Flask】Flask-SQLAlchemy的增删改查(CRUD)操作
2022-08-03 05:10:00 【중둑【上瘾】】
增加(Create)
1.创建 Python 对象的一个实例
2.把添加实例告诉会话
3.提交会话
from models import User
user1 = User('admin', '[email protected]')
db.session.add(user1)
db.session.commit()
修改(Update)
1.查询要修改的对象的实例
2.把修改实例属性的操作告诉会话
3.提交会话
from models import User
user1 = User.query.filter(User.username == 'admin').first()
user1.username = 'admin_new'
db.session.commit()
删除(Delete)
1.查询要删除的对象的实例
2.把删除操作告诉会话
3.提交会话
from models import User
user1 = User.query.filter(User.username == 'admin').first()
db.session.delete(user1)
db.session.commit()
检索(Retrieve)
参照官网给出的示例进行总结,假定数据库中有如下数据:
id | username | |
---|---|---|
1 | admin | [email protected] |
2 | peter | [email protected] |
3 | guest | [email protected] |
通过用户名查询用户,查询一个不存在的用户名返回 None。
>>> peter = User.query.filter_by(username='peter').first()
>>> peter.id
1
>>> peter.email
u'[email protected]'
>>> missing = User.query.filter_by(username='missing').first()
>>> missing is None
True
查询email属性以@example.com结尾的用户,.all()将返回一个对象组成的列表
>>> User.query.filter(User.email.endswith('@example.com')).all() # 返回一个列表
[<User u'admin'>, <User u'guest'>]
按某种规则对用户排序
>>> User.query.order_by(User.username)
[<User u'admin'>, <User u'guest'>, <User u'peter'>]
限制返回用户的数量。
>>> User.query.limit(1).all()
[<User u'admin'>]
用主键查询用户。
>>> User.query.get(1)
<User u'admin'>
边栏推荐
猜你喜欢
接口管理工具YApi怎么用?颜值高、易管理、超好用
Kaggle 入门(Kaggle网站使用及项目复现)
Modified BiotinDIAZO-Biotin-PEG3-DBCO|diazo-biotin-tripolyethylene glycol-diphenylcyclooctyne
Interface test practice | Detailed explanation of the difference between GET / POST requests
集合框架知识
typescript40-class类的保护修饰符
Build your own web page on raspberry pie (1)
Common fluorescent dyes to modify a variety of groups and its excitation and emission wavelength data in the data
Ali cloud object storage oss private barrels to generate links
High availability, two locations and three centers
随机推荐
shell script loop statement
Kaggle(四)Scikit-learn
Redis6学习笔记
MCM box model modeling method and source analysis of atmospheric O3
Flink state
Junit
1058 选择题 (20 分)(C语言)
Interface Test Framework Practice (4) | Get Schema Assertion
BIOTIN ALKYNE CAS: 773888-45-2 Price, Supplier
Installation of Apache DolphinScheduler version 2.0.5 distributed cluster
网络流媒体下载的 10 种方法(以下载 Echo 音乐为例)
高效率科研神器——小软件、大能量
MySql数据库
4.如何避免缓存穿透、缓存击穿、缓存雪崩
Gradle的安装配置
Online password generator tool recommendation
Interface test practice | Detailed explanation of the difference between GET / POST requests
接口测试框架实战(二)| 接口请求断言
Apache DolphinScheduler版本2.0.5分布式集群的安装
Kaggle 入门(Kaggle网站使用及项目复现)