单表操作

@app.route("/add_book")
def add_book():
    ro1 = Books(name='三国演义')#增加Books中name为三国演义的数据
    db.session.add(ro1)#增加
    db.session.commit()#提交
    return "添加成功"

 

@app.route("/del_book")
def del_book():
    rol = Books.query.filter_by(name="水浒传").first()#删除Books中name为水浒传的数据,其中query固定写法,first第一个
    db.session.delete(rol)#删除
    db.session.commit()#提交
    return "删除成功"

 

@app.route("/alter_book")
def alter_book():
    rol = Books.query.filter_by(name="三国演义").first()#与删除大致相同
    rol.name = "射雕英雄传"#更改内容
    db.session.commit()#提交
    return "修改成功"

 

SQLAlchemy中关于查询分为两部分:一个是查询过滤器,一个是查询执行器。

过滤器

过滤器说明
filter() 把过滤器添加到原查询上,返回一个新查询
filter_by() 把等值过滤器添加到原查询上,返回一个新查询
limit 使用指定的值限定原查询返回的结果
offset() 偏移原查询返回的结果,返回一个新查询
order_by() 根据指定条件对原查询结果进行排序,返回一个新查询
group_by() 根据指定条件对原查询结果进行分组,返回一个新查询

执行器

方法说明
all() 以列表形式返回查询的所有结果
first() 返回查询的第一个结果,如果未查到,返回None
first_or_404() 返回查询的第一个结果,如果未查到,返回404
get() 返回指定主键对应的行,如不存在,返回None
get_or_404() 返回指定主键对应的行,如不存在,返回404
count() 返回查询结果的数量
paginate() 返回一个Paginate对象,它包含指定范围内的结果

 

一对多表

在多的一方创建一个字段指向另一个表中的唯一标识(id),外键

增删与单表操作大致相同

查询数据

@app.route("/select_book")
def select_book():
    # 目标:查询南方出版社出版的书籍
    res = Publishers.query.filter(Publishers.name == "南方出版社").first()
    rols = Books.query.filter(Books.publish_id == res.id).all()
    print(rols)
    return "查询成功"

简:在表中设置字段时添加一个内容(红色),操作方法变简

class Publishers(db.Model):
    __tablename__ = 'publishers'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64))
    city = db.Column(db.String(64))
    to_book = db.relationship("Book")#Book是表模型类名

    def __repr__(self):
        return 'User:%s' % self.name

@app.route("/select_book")
def select_book():
    # 目标:查询南方出版社出版的书籍
    res = Publishers.query.filter(Publishers.name == "南方出版社").first().to_book
    print(res)
    return "查询成功"

 

class Publishers(db.Model):
    __tablename__ = 'publishers'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64))
    city = db.Column(db.String(64))
    to_book = db.relationship("Book",backref="to_pub")#Book是表模型类名,backref是反向查询,不用在Book的表查询pub再复制relationship的代码

    def __repr__(self):
        return 'User:%s' % self.name

@app.route("/select_book")
def select_book():
    # 目标:查询南方出版社出版的书籍
    res = Publishers.query.filter(Publishers.name == "南方出版社").first().to_book
    print(res)
    return "查询成功"

 多对多

新建一张表用多个外键将多张表关联

class Bookspri(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    book_id=db.Column(db.Integer,db.ForeignKey("book.id"))#设置外键,表名.字段名
    author_id=db.Column(db.Integer,db.ForeignKey("author.id"))#设置外键,表名.字段名

 (删除book中的一行内容会将关联的内容也删除)

(使用relationship关联第三张表的secondary="author__book"其中自动的表名下划线会将一个变成两个,除非自己使用__tablename__设置表名)

from flask import Flask
from flask_sqlalchemy import SQLAlchemy


class Config(object):
    DEBUG = True
    SQLALCHEMY_DATABASE_URI = "mysql://root:mysql@127.0.0.1:3306/demo1"
    SQLALCHEMY_TRACK_MODIFICATIONS = False


app = Flask(__name__)
app.config.from_object(Config)
db = SQLAlchemy(app)


# 图书表
class Book(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(64), nullable=False)
    price = db.Column(db.Integer)
    pub_id = db.Column(db.Integer, db.ForeignKey("publisher.id"))
    # to_pub = db.relationship("Publisher")
    authors = db.relationship("Author", secondary="author__book", backref="books")

    def __repr__(self):
        return "图书名:%s|价格为%s" % (self.title, self.price)


# 出版社表
class Publisher(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), nullable=False)
    address = db.Column(db.String(64), nullable=False)
    to_books = db.relationship("Book", backref="to_pub")


# 作者表
class Author(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), nullable=False)
    age = db.Column(db.Integer)


class Author_Book(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    author_id = db.Column(db.Integer, db.ForeignKey("author.id"))
    book_id = db.Column(db.Integer, db.ForeignKey("book.id"))


@app.route("/", methods=["GET", "POST"])
def index():
    # 查询南方出版社出版的所有书籍
    # res = Publisher.query.filter_by(name="南方出版社").first().to_books
    # res = Book.query.filter(Book.pub_id == pub.id).all()

    # 查询渣男日记的出版社名
    # book = Book.query.filter_by(title="渣男日记").first()
    # res = Publisher.query.filter_by(id=book.pub_id).
    # res = Book.query.filter_by(title="渣男日记").first().to_pub
    # print(res)

    # 增加
    # new_obj = Author_Book()
    # new_obj.author_id = Author.query.filter_by(name="小黑").first().id
    # new_obj.book_id = Book.query.filter_by(title="渣男日记").first().id
    #
    # new_obj1 = Author_Book()
    # new_obj1.author_id = Author.query.filter_by(name="小川").first().id
    # new_obj1.book_id = Book.query.filter_by(title="渣男日记").first().id
    #
    # db.session.add(new_obj)
    # db.session.add(new_obj1)
    # db.session.commit()
    # res = Book.query.filter_by(title="渣男日记").first().authors
    # print(res)

    # new_book = Book()
    # new_book.title = "20人工日记"
    # new_book.price = 999
    # new_book.pub_id = 1
    # new_book.authors = Author.query.all()
    # db.session.add(new_book)
    # db.session.commit()

    # book = Book.query.filter_by(title="渣男日记").first()
    # book.authors = Author.query.all()
    # db.session.commit()

    # book = Book.query.filter_by(title="金").first()
    # book.authors = Author.query.filter_by(name="小黑").first()   # 错误,必须是列表
    # db.session.commit()

    # new_book = Book()
    # new_book.title = "20人工日记2"
    # new_book.price = 888
    # new_book.pub_id = 1
    # new_book.authors = [Author(name="老五", age=20), Author(name="老liu", age=20)]
    # db.session.add(new_book)
    # db.session.commit()

    # book = Book.query.filter_by(title="20人工日记2").first()
    # db.session.delete(book)
    # db.session.commit()


    res = Author.query.filter_by(name="小黑").first().books

    print(res)
    return "成功!"


if __name__ == '__main__':
    db.create_all()
    app.run()
总代码

 

 

 

 

posted on 2022-05-10 16:20  今晚不吃饭  阅读(31)  评论(0编辑  收藏  举报