《Flask Web Development》学习笔记---chapter5 Database

本文介绍了使用Flask框架结合SQLAlchemy ORM进行数据库操作的方法,包括表定义、增删改查等基本操作,并探讨了数据库迁移的过程。

1. 分析各种数据库,Relational databases 和 NoSQL databases。


2. 用Flask-SQLAlchemy


3.  Model Definition  和  Relationships


4. Database Operations

1. 创建表

from models import db
db.drop_all()
db.create_all()
如果某张表已经在数据库存在,db.create_all()是不会re-create或者update它的。所以只有先db.drop_all()
P.S:所以要学 database migration

2.插入

对象实例:

u= User(xxxxx)
加入session:

db.session.add(u)
将操作提交数据库:

db.session.commit()

新知识

一次性加入session

db.session.add_all([u1, u2, u3, u4, u5])


3. error occurs

db.session.rollback()
到底会回退到什么状态?不知道,懒得查,求解答

4. 删除

db.session.delete(u)
db.session.commit()


5.  查询

>>> User.query.all()
[<User u'john'>, <User u'susan'>, <User u'david'>]
过滤条件

>>>User.query.filter_by(role=user_role).all()
[<User u'susan'>, <User u'david'>]
检查SQL query语句

>>> str(User.query.filter_by(role=user_role))
'SELECT users.id AS users_id, users.username AS users_username,
users.role_id AS users_role_id FROM users WHERE :param_1 = users.role_id'


6.  常用SQLAlchemy 查询过滤器

filter()             Returns a new query that adds an additional filter to the original query 
filter_by()          Returns a new query that adds an additional equality filter to the original query
limit()              Returns a new query that limits the number of results of the original query to the given number
offset()             Returns a new query that applies an offset into the list of results of the original query
order_by()           Returns a new query that sorts the results of the original query according to the given criteria
group_by()           Returns a new query that groups the results of the original query according to the given criteria                  

7. 常用SQLAlchemy 查询执行器
all()          Returns all the results of a query as a list
first()        Returns the first result of a query, or None if there are no results
frist_or_404()     没结果就报404
get()          Returns the row that matches the given primary key, or None if no matching row is found
get_or_404         没结果就报404
count()        Returns a Pagination object that contains the specified range of results


5. 用Flask-Migrate 进行数据库迁移

等看了flask-migrate文档再说。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值