ORM的:增、删、改、查

“”"
增:
语法:实例化类Author传递以字段为参数的数据进去:类名(字段名1=‘数据1’,字段名2=‘数据2’)
new_author1 = Author(name=‘小明’) # id=1
new_author2 = Author(name=‘小华’) # id=2
id自动生成的,不需要传递

有外键的表的增加:
new_book1 = Book(title=‘小明的第一本书籍’, author_id=1)
new_book2 = Book(title=‘小明的第二本书籍’, author_id=1)
new_book3 = Book(title=‘小华的第一本书籍’, author_id=2)
db.session.add_all([new_book1,new_book2,new_book3])
title是通过表单传递过来的,需要用post方式接收:request.form.get(‘title’)
author_id是通过地址栏传递过来的,需要通过get方式接收:request.args.get(‘author_id’)

删:
语法:db.session.delete(对象)
对象需要通过id获取
一般是get方式接收此id
request.args.get(‘author_id’) # 获取到某个作者的id
通过id获取此作者的记录(对象)Author.query.get(主键id) 赋值给one_author
db.session.delete(one_author)

改:
get:
获取作者对象
对象需要通过id获取
一般是get方式接收此id
request.args.get(‘author_id’) # 获取到某个作者的id
通过id获取此作者的记录(对象)Author.query.get(主键id) 赋值给one_author

post:
post方式提交要修改的字段name
接收name=request.form.get(‘name’)
修改操作:对象.字段名 one_author.name=name
db.session.add(one_author)

查:
语法:类.query.order_by(类.字段名.desc()).all()
users = User.query.order_by(User.id.desc()).all()
不需要任何参数
获取之后在模板遍历输出即可。
重点一般是在此视图函数的模板页面进行url的拼接
“”"

猜你喜欢

转载自blog.csdn.net/weixin_44754855/article/details/90173701