django是有orm操做的 可想而知 那么flask也是有orm操做的,其实flask的orm操做的使用和djnago的是差很少的 html
django的orm操做进行条件筛选的时候后面跟着的是objectspython
django
表名.objects.语句
flask的是query
表名.objects.语句
eg:
django:
User.objects.filter(条件).first
flask:
User.query.filter_by(条件).first
经常使用查询语句:sql
all() 查询全部 filter_by / filter 单个查询 filter_by 不须要指定是哪一个类的哪一个属性,只须要制定属性及其目标值就能够了, 而且只能写具体的值不能写模糊值 filter filter中指定查询条件的时候须要指定类名的前缀。能够指定模糊值 order_by 排序
类名.query获得的结果就为原始查询集django
加上各类的过滤器的方法 最终返回的结果 为数据查询集 都使用数据查询集flask
类名.query.all()app
User.query.all() # 查询User表中的全部数据
类名.query.filter([类名.属性名 条件操做符 值])spa
User.query.filter() #返回全部 User.query.filter(User.age>20) #查询年龄大于20的数据 User.query.filter(User.age>20,User.age<40) #查询年龄大于20的数据 and 小于40
类名.query.filter_by(属性名=值...)code
data = User.query.filter_by(id=2) data = User.query.filter_by(id>2) #错误写法 不能够使用模糊查到 data = User.query.filter_by(id=2,age=27)
offset(num)orm
User.query.filter().offset(2)
limit(num)htm
User.query.filter(User.age>30).limit(2) 查到的结果只取两个
User.query.offset(2).limit(2) 也是只取两个
默认是升序
data = User.query.order_by(User.age) #升序
data = User.query.order_by(-User.age) #降序
User.query.first() == User.query.get(2)
查询成功返回对象 查询失败 返回None
User.query.get(2)
User.query.filter(User.username.contains('7')) #username中包含数字7的数据
User.query.filter(User.username.like('李%')) #以李做为开头的
User.query.filter(User.username.startswith('李')) # 以姓李的开头 User.query.filter(User.username.endswith('6')) # 以6为结尾的
__gt__
__ge__
__lt__
__le__
>
<
>=
<=
==
!=
.
User.query.filter(User.age.in_([27,12,1,30,40,50]))
User.query.filter(User.username.isnot(None))
多个条件 用逗号隔开,为and操做
from sqlalchemy import and_
User.query.filter(and_(User.age==27,User.id==2))
from sqlalchemy import or_
@main.route('/and/') def myAnd(): data = User.query.filter(or_(User.age==27,User.id==2)) data = User.query.filter(and_(User.username.like('%6%')),or_(User.age>=27,User.id==2)) return render_template('show.html',data=data)
from sqlalchemy import not_
@main.route('/and/') def myAnd(): # data = User.query.filter(not_(User.age>27,User.id==1))\ #错误写法只能给一个条件取反 data = User.query.filter(not_(User.age>27)) return render_template('show.html',data=data)
data = User.query.filter(not_(User.age>27)).count()
模块:
pip install flask-migrate
pip install flask-script
from flask_migrate import Migrate,MigrateCommand from flask_sqlalchemy import SQLalchemy app = Flask(__name__) db = SQLalchemy(app) migrate = Migrate(app,db=db) manager = Manager(app) manager.add_command('db',MigrateCommand)
python manage.py db init
python manage.py db migrate
python manage.py db upgrade
注意
若是当前存在 模型 可是执行建立迁移文件的时候 提示没有任何改变的时候 须要查看当前的模型类是否有使用(导入)