flask資料庫模型

2021-09-29 01:32:58 字數 2743 閱讀 5986

web程式中使用資料庫儲存資料,在檢視函式中運算元據庫。如果在檢視函式中編寫sql語句,則**顯得太混亂,所以開發者 將資料庫中的table對映成python類,將column對映成類的屬性,row對映成類的例項,所以就可以通過操作python類物件實現對資料庫的操作。

table在對映為類,所以建表就是定義類

class user(db.model):

id=db.column(db.integer,primary_key=true)

sqlalchemy常用的字段型別有integer,string,text,time,data,datatime,boolean,float

資料庫的基本操作crud,

create:

user=user(name=『zhang』)

db.session.add(user)

db.session.commit()

read:

常用的過濾方法:

filter() filter是最基本的過濾方式,它使用指定的規則來過濾記錄。如user.query.filter(user.name==『zhang』).all()

filter_by() filter_by()比filter()更好用,因為直接使用欄位名稱,可以使用各種表示式。 user.query.filter——by(name=『zhang』 and telnum=『19987657767』).all()

order_by() 根據指定規則進行排序,返回結果

limit(limit)

group_by()

offset(offset)

常用的查詢方法:

all();

first();

one()(只允許有一條記錄,如果記錄數不等於1.則丟擲錯誤)

get(id);

count()(返回查詢結果的數量);

one_or_none(如果 結果不為1,不丟擲錯誤,而是返回none

first_or_404();

get_or_404(id);

paginate()(返回乙個pagination物件,可以對記錄進行分頁處理);with_parent(instance)(傳入模型類例項作為引數,返回和這個例項相關聯的物件)

update

user=user.query.get(3)

user.name=『zhangyuanbin』

db.session.commit()

delete

user=user.query.get(3)

db.session.delete(user)

db.session.commit()

沒有關係,各個表就是一張張死表。通過建立關係,可以讓不同表之間的字段建立聯絡。

1.一對多關係;多的 一側設定 外來鍵

class writer(db.model):

books=db.relationship(『book』,back_populates=『writer』)

class book(db.model):

writer_id=db.column(db.integer,db.foreignkey(『writer.id』))

writer=db.relationship(『writer』,back_populations=『books』)

2.一對一關係;設定乙個外來鍵,也不用back-populations,因為一對一,對應的關係只能是它。

class country(db.model):

capital=db.relationship(『capital』,uselist=false)

class capital(db.model):

country_id=db.column(db.integer,db.foreignkey(『country.id』))

country=db.relationship(『country』)

3.多對多關係

association_table=db.table(『association』,db.column(『student_id』,db.integer,db.foreignkey(『student.id』)),db.column(『teacher_id』,db.integer,db.foreignkey(『teacher.id』)))

class student(db.model):

teachers=db.relationship(『teacher』,secondary=association_table,back_populates=『students』)

class teacher(db.model):

students=db.relationship(『student』,secondary=association_table,back_populates=『teachers』)

多對多關係是兩個一對多關係的合成。在 關聯表association_table中有兩個外來鍵,分別為兩張表的id 字段。secondary=association_table,back_populates=』』

students_id

teachers_id11

1224

1323

2114

students一對多association_table(students_id)一對一(teachers_id)

teachers一對多association_table(teachers_id)一對一(students_id)

通過association_table這個『中間人』,利用兩個一對多,實現了多對多。

Flask 模型 資料庫查詢 常見查詢

目錄方法 all fifirst get 字段列表 別名distinct 返回列表,包含所有物件 用法 類名.query.all db.session.query 模型名 all u user.query.all 0 2 u user.query.all u db.session.query use...

flask 資料庫模型建立和匯入

匯入sqlalchemy from flask sqlalchemy import sqlalchemy 生成資料庫訪問物件db db sqlalchemy 定義表物件 class comment db.model tablename comment id db.column db.integer,...

Flask資料庫遷移

在開發過程中,需要修改資料庫模型,且還要在修改之後更新資料庫。最直接的 式就是刪除 舊表,但這樣會丟失資料。更好的解決辦法是使 資料庫遷移框架,它可以追蹤資料庫模式的變化,然後把變動應 到資料 庫中。在flask中可以使 flask migrate擴充套件,來實現資料遷移。並且整合到flask sc...