Flask对数据库的查询以及关联

数据库的查询

  1. 首先创建一个模型类
# 用户
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))
  1. 创建好之后开始执行以下代码
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()

		# 赛选 like
		# user = User.query.filter(User.name.like('%张%')).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')

一对多关联

  1. 创建两个表进行链接
# 专业模型
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'))

  1. 链接好之后执行以下代码
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')  

你可能感兴趣的:(flask,数据库,python)