当前位置:网站首页>【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'>
边栏推荐
猜你喜欢

Redis6学习笔记

Kaggle 入门(Kaggle网站使用及项目复现)

UV decomposition of biotin - PEG2 - azide | CAS: 1192802-98-4 biotin connectors

Super handy drawing tool is recommended

Secondary development of WinForm controls

13.< tag-动态规划和回文字串>lt.647. 回文子串 + lt.516.最长回文子序列

Power button 561. An array of split

Interface Test Framework Practice (4) | Get Schema Assertion

Shell conditional statement judgment

Interface test practice | Detailed explanation of the difference between GET / POST requests
随机推荐
建造者模式(Builder Pattern)
背压机制
生活原则。
获取Ip工具类
第三次HarmonyOS培训
closures in js
Installation of Apache DolphinScheduler version 2.0.5 distributed cluster
ss-5.consul服务端+生产者+消费者
VSO Downloader Ultimate 5.0.1.45 中文多语免费版 在线视频下载工具
MySql数据库
minio下载文件乱码或者是一条横线
Create a tree structure
接口和抽象
Bubble sort in c language structure
Build your own web page on raspberry pie (1)
The problem that the rosbag tool plotjuggler cannot open rosbag
Detailed explanation of MOSN reverse channel
Build your own web page on the Raspberry Pi (2)
vim命令
Gradle的安装配置