当前位置:网站首页>Flask对数据库的查询以及关联
Flask对数据库的查询以及关联
2022-07-27 05:02:00 【pink_Pig___】
数据库的查询
- 首先创建一个模型类
# 用户
class User(db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement=True, comment="ID")
name = db.Column(db.String(32), nullable=False, default='')
age = db.Column(db.Integer)
balance = db.Column(db.DECIMAL(10, 2))
- 创建好之后开始执行以下代码
class Users(Resource):
def get(self):
# 查询一个名叫张三的用户
# user = User.query.filter_by(name='张三').first()
# 查询多个名叫张三的用户
# user = User.query.filter_by(name='张三').all()
# 获取所有数据
# user = User.query.all()
# filter的查询
# user = User.query.filter(User.name == '张三').all()
# 添加展示限制
# user = User.query.limit(3).all()
# 偏移
# user = User.query.offset(1).all()
# 分类页逻辑
# 第一页 0,2 (页面-1)* 每页条数
# 第一页 2,2
# 第一页 4,2
# 第一页 6,2
# page = 2
# page_size = 2
# offset = (page - 1) * page_size
# user = User.query.offset(offset).limit(page_size).all()
# or_、and_、not_、的判断
# from sqlalchemy import or_, and_, not_
# user = User.query.filter(or_(User.name == '张三', User.name == '王五')).all()
# user = User.query.filter(and_(User.name == '张三', User.balance == '1000')).all()
# user = User.query.filter(not_(User.name == '张三')).all()
# 比较查询
# user = User.query.filter(User.age.__lt__(18)).all() # 小于18
# user = User.query.filter(User.age.__le__(18)).all() # 小于等于18
# user = User.query.filter(User.age.__gt__(18)).all() # 大于18
# user = User.query.filter(User.age.__ge__(18)).all() # 大于等于18
# in_操作 查询在 里面的
# user = User.query.filter(User.name.in_(('张三', '王五'))).all()
# 统计数据
# from sqlalchemy import func
# count = db.session.query(func.count(User.id)).first()[0] # 统计数据的行数
# count = db.session.query(func.avg(User.age)).first()[0] # 计算平局数
# count = db.session.query(func.max(User.age)).first()[0] # 最大值
# count = db.session.query(func.min(User.age)).first()[0] # 最小值
# print(count)
# 还可以写入SQL语句
# sql = 'select * from user where age > 18'
# rs = db.session.execute(sql)
# for item in rs:
# print(item['name'])
# 使用order_by进行排序asc()升序,默认asc()
# User.query.order_by(User.age.asc()).all()
# 降序desc()
# User.query.order_by(User.age.desc()).all()
# data = marshal(user, {
# 'id': fields.Integer,
# 'name': fields.String,
# 'age': fields.Integer,
# 'balance': fields.Float
# })
#
# return jsonify({'data': data})
api.add_resource(Users, '/users')
一对多关联
- 创建两个表进行链接
# 专业模型
class Sub(db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement=True, comment='专业ID')
name = db.Column(db.String(32), comment='专业名称')
stu = db.relationship('Stu', backref='sub')
# 学生模型
class Stu(db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement=True, comment='学生ID')
name = db.Column(db.String(32), comment='学生名称')
age = db.Column(db.Integer, comment='学生年龄')
sub_id = db.Column(db.Integer, db.ForeignKey('sub.id'))
- 链接好之后执行以下代码
class Users():
def get(self):
# s1 = Sub(name='人工智能')
# s2 = Sub(name='抽截图的')
# s3 = Sub(name='掉头发的')
#
# stu1 = Stu(name='张三', age=18, sub_id=1)
# stu2 = Stu(name='李四', age=21, sub_id=2)
# stu3 = Stu(name='王五', age=33, sub_id=3)
#
# db.session.add_all([s1,s2,s3])
# db.session.add_all([stu1, stu2, stu3])
#
# db.session.commit()
# 正向查询,从一方,查出多方信息
# sub_info = Sub.query.filter(Sub.name == '人工智能').first()
# stu_info = Stu.query.filter(Stu.id == 1).first()
# print(stu_info.sub.name)
# print(sub_info.id)
# print(sub_info.name)
# 反向查询
# sub_info = Sub.query.filter(Sub.name == '人工智能').first()
# print(dir(sub_info))
# print(sub_info.stu)
# for item in sub_info.stu:
# print(item.name, item.age)
api.add_resource(Users, '/users')
多对多
# 中间件
article_tag = db.Table(
'article_tag',
db.Column('article_id', db.Integer, db.ForeignKey('article.id'), primary_key=True),
db.Column('tag_id', db.Integer, db.ForeignKey('tag.id'), primary_key=True)
)
# 文章表
class Article(db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
title = db.Column(db.String(32), comment='文章名')
tags = db.relationship('Tag', secondary=article_tag, backref='articles')
# 标签表
class Tag(db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(32), comment='标签名')
多对多的查询
class User(Resource):
def get(self):
# 查询
# 标签查文章
# tag_info = Tag.query.filter(Tag.id == 1).first()
# # print(tag_info.name)
# print(tag_info.articles) # 文章内容
# for item in tag_info.articles:
# print(item.title)
# 文章查标签
article_info = Article.query.filter(Article.id == 1).first()
# print(article_info.title)
print(article_info.tags) # 标签的内容
for item in article_info.tags:
print(item.name)
api.add_resource(Users, '/users')
边栏推荐
- 知识点总结(一)
- Critical path principle
- JVM Part 1: memory and garbage collection part 7 -- runtime data area heap
- 听过最自律的一句话: 那些我难以言表 不作声响
- B1022 D进制的A+B
- Scientific Computing Library -- Matplotlib
- Demo of throttling function -- regular expression matching
- Solution and principle analysis of feign call missing request header
- redis事务
- 如何快速有效解决数据库连接失败问题
猜你喜欢

素数筛选(埃氏筛法,区间筛法,欧拉筛法)

Message reliability processing

Database connection pool & Druid usage

A math problem cost the chip giant $500million

ERP system brand

2021 OWASP top 5: security configuration error

JVM上篇:内存与垃圾回收篇--运行时数据区四-程序计数器

数据库连接池&&Druid使用

JVM Part 1: memory and garbage collection part 3 - runtime data area - overview and threads

JVM Part 1: memory and garbage collection part 9 - runtime data area - object instantiation, memory layout and access location
随机推荐
Message reliability processing
Machine learning overview
268.missing number of leetcode
JVM上篇:内存与垃圾回收篇五--运行时数据区-虚拟机栈
The difference between strlen and sizeof
B1026 program running time
35. Scroll
李宏毅机器学习组队学习打卡活动day03---误差和梯度下降
Differences and examples between internal classes and static internal classes
Explore the mysteries of the security, intelligence and performance of the universal altek platform!
JVM上篇:内存与垃圾回收篇十--运行时数据区-直接内存
redis持久化
B1023 group minimum
Shell course summary
pyside2____1.安装和案列
Critical path principle
ssm框架整合
JDBC API 详解
实用小工具: Kotlin 代码片段
Could not autowire.No beans of ‘userMapper‘ type found.