03-Flask之數(shù)據(jù)模型

一、Flask-Migrate插件(模型遷移)

- 數(shù)據(jù)遷移
    Django中,模型創(chuàng)建好只需要創(chuàng)建遷移文件,執(zhí)行遷移文件即可;
    falsk中,模型創(chuàng)建好之后,通過執(zhí)行程序調(diào)用db.create_all();
    flask是否有遷移?
    通過flask-migrate插件,即可實現(xiàn);
    
- 安裝flask-migrate
    pip install flask-migrate
    
- 初始化
    # ext.py文件中
    from flask_migrate import Migrate
    migrate = Migrate()
    def init_ext(app):
        migrate.init_app(app,db)
        
- 配置flask-migrate命令操作
    # manager.py文件中
    from flask_migrate import MigrateCommand
    manager.add_command('db', MigrateCommand)
    
- flask-migrate命令相關(guān)
    # 生成對應(yīng)的文件目錄(只需要調(diào)用一次)
    python manage.py db init
    # 生成遷移文件
    python manage.py db migrate
    # 生成遷移文件(mesage添加標注信息)
    python manage.py db migrate --mesage 'xxx'
    # 執(zhí)行遷移中的升級(創(chuàng)表過程)
    python manage.py db upgrade
    # 執(zhí)行遷移中的降級(刪表過程)
    python manage.py db downgrade

二、SQLAlchemy數(shù)據(jù)定義

  • 字段
類型名稱        python類型          描述
Integer         int                 常規(guī)整形,通常為32位
SmallInteger    int                 短整形,通常為16位
BigInteger      int或long           精度不受限整形
Float           float               浮點數(shù)
String          str                 可變長度字符串
Text            str                 可變長度字符串,適合大量文本
Boolean         bool                布爾型
Date            datetime.date       日期類型
Time            datetime.time       時間類型
Interval        datetime.timedelta  時間間隔
PickleType      任意Python對象      自動Pickle序列化
LargeBinary     str                 二進制
  • 約束
可選參數(shù)        描述
primary_key     如果設(shè)置為True,則為該列表的主鍵
unique          如果設(shè)置為True,該列不允許相同值
index           如果設(shè)置為True,為該列創(chuàng)建索引,查詢效率會更高
nullable        如果設(shè)置為True,該列允許為空。如果設(shè)置為False,該列不允許空值
default         定義該列的默認值
ForeignKey      外鍵(用來約束級聯(lián)數(shù)據(jù))

三、SQLAlchemy基本操作

- 創(chuàng)建表單
    db.create_all()

- 刪除表單
    db.drop_all()
    
- 插入一個數(shù)據(jù)
    db.session.add(obj)
    db.session.commit()
    
- 插入一組數(shù)據(jù)
    db.session.add_all(list[obj])
    db.session.commit()
    
- 刪除一個數(shù)據(jù)
    db.session.delete(obj)
    db.session.commit()
    
    例如:
    def deletedata():
        person = Person.query.first()

        db.session.delete(person)
        db.session.commit()

        return "刪除一個數(shù)據(jù)成功!"

修改和刪除其都是基于查詢。

四、SQLAlchemy數(shù)據(jù)查詢

  • 查詢數(shù)據(jù)結(jié)果集
- 語法
    模型類.query.xxx

- 獲取結(jié)果集
    # 所有數(shù)據(jù)
    all()   
    # 按條件查詢
    filter(模型類.屬性.運算符('xxx'))
    filter(模型類.屬性 運算符 值)

- 獲取所有數(shù)據(jù)
    模型類.query.all()
    persons = Person.query.all()

- 比較運算符
    模型類.query.filter(模型類.屬性 運算符 xxx)
    persons = Person.query.filter(Person.score > 90)
    persons = Person.query.filter(Person.name == '1883-小三')

- 以xxx開頭
    模型類.query.filter(模型類.屬性.startswith('xxx'))
    persons = Person.query.filter(Person.name.startswith('1'))
    
- 以xxx結(jié)尾
    模型類.query.filter(模型類.屬性.endswith('xxx'))
    persons = Person.query.filter(Person.score.endswith('7'))
    
- 包含xxx
    模型類.query.filter(模型類.屬性.contains('xxx'))
    persons = Person.query.filter(Person.score.contains('7'))
    
- 在xxx其中一個 數(shù)據(jù)庫中的in
    模型類.query.filter(模型類.屬性.in_([xxx,xxx,xxx]))
    persons = Person.query.filter(Person.id.in_([2,3,4]))
    
- 模糊查詢 數(shù)據(jù)庫中的like
    模型類.query.filter(模型類.屬性.like('xxx'))
    persons = Person.query.filter(Person.name.like('17%'))
  • 獲取單個數(shù)據(jù)
- 第一行數(shù)據(jù)
    模型類.query.first()
    person = Person.query.first()

- 通過主鍵獲取一個數(shù)據(jù)
    模型類.query.get()
    person = Person.query.get(2)
  • 數(shù)據(jù)篩選
- 限制數(shù)據(jù)個數(shù) 數(shù)據(jù)庫中的limit
    模型類.query.limit()
    persons = Person.query.limit(5)
    
- 排序 數(shù)據(jù)庫中的order_by
    模型類.query.order_by()
    persons = Person.query.order_by('id')
    persons = Person.query.order_by('-id')
    
    persons = Person.query.order_by(Person.id) 
    persons = Person.query.order_by(-Person.id) 
    
    備注: 不管是放在哪個位置,limit都是最后一個操作!
    # 下面兩個操作都是一樣的
    # 先排序,后偏移,最后再取數(shù)據(jù)
    persons = Person.query.order_by('-id').limit(5).offset(5)
    persons = Person.query.order_by('-id').offset(5).limit(5)
    
- 偏移(跳過前面n條數(shù)據(jù))
    模型類.query.offset()
    # 跳過前面5條數(shù)據(jù)
    persons = Person.query.offset(5)

offset和limit不區(qū)分順序,offset先生效

五、SQLAlchemy數(shù)據(jù)之級聯(lián)查詢

  • relationship關(guān)聯(lián)操作
# lazy懶加載方式
db.relationship('聲明級聯(lián)數(shù)據(jù)', backref='表名', lazy=True)

# 班級模型類
class Grade(db.Model):
    # 主鍵
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    # 班級名稱 python1811   ios1803
    g_name = db.Column(db.String(20))

    # 但這不需要再進行遷移,就是執(zhí)行遷移,也會提示沒有任何改變
    g_students = db.relationship('Student', backref='grade', lazy=True)

# 學(xué)生模型類
class Student(db.Model):
    # 主鍵
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    # 名字
    s_name = db.Column(db.String(20))
    # 成績
    s_score = db.Column(db.Integer)
    # 班級(外鍵)
    s_grade = db.Column(db.Integer, db.ForeignKey(Grade.id))

級聯(lián)查詢flask中和django最大的區(qū)別是,django把對應(yīng)該生成的生成好,flask需要做操作!

  • 數(shù)據(jù)的獲取
# 獲取對應(yīng)班級中的學(xué)生信息

# 方式一: 通過查詢Student中s_grade與對應(yīng)班級號相同的
students = Student.query.filter(Student.s_grade==gradeid)

# 方式二: 通過級聯(lián)查詢(獲取到對應(yīng)班級,班級學(xué)生信息就是g_students中)
students = Grade.query.get(gradeid).g_students
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容