摘要: 到目前為止,當我們的程序涉及到數(shù)據(jù)庫相關(guān)操作時,我們一般都會這么搞:
創(chuàng)建數(shù)據(jù)庫,設(shè)計表結(jié)構(gòu)和字段使用 MySQLdb 來連接數(shù)據(jù)庫,并編寫數(shù)據(jù)訪問層代碼業(yè)務(wù)邏輯層去調(diào)用數(shù)據(jù)訪問層執(zhí)行數(shù)據(jù)庫操作目錄:
建立ModelsModels 增Models 刪Models 改Models 查內(nèi)容: 一.建立Models
from app.models import myclassclass myclass(): aa = models. CharField (max_length=None) bb = models. CharField (max_length=None) def __unicode__(self): return u'%s %s' %(aa,bb)二.Models 增 添加一行數(shù)據(jù)1 add = myclass(aa=’wahaha’,bb=’hahawa’ ) add.save() #不save無法保存到數(shù)據(jù)庫 add.id #獲取增加的這條數(shù)據(jù)的ID 添加一行數(shù)據(jù)2 myclass.objects.create(aa=’wahaha’,bb=’hahawa’) # 同上1方法一樣無需保存save
三.Models 刪 刪除表中全部數(shù)據(jù) myclass.objects.all().delete() 刪除一條aa等于’test’的數(shù)據(jù) myclass.objects.get(aa=’test’).delete() 刪除多條數(shù)據(jù) myclass.objects.filter(aa=’123’).delete() #過濾出aa字段等于123的都刪除
四.Models 改
更新數(shù)據(jù) a = userinfo.objects.get(cellPhone=’13133333333’) #查詢一條你要更新的數(shù)據(jù) a.cellPhone=’3111111111111’ #賦值給你要更新的字段 a.save() #保存 更新多個字段或一個字段 myclass.objects .get(aa=’123’).update(aa=’321’,bb=”wahaha”) #update可多條 更新所有字段 myclass.objects.all().update(aa=’8888’) #更新所有字段,更新后會顯示受影響的條數(shù)
五.Models 查 查出庫中所有條數(shù)的數(shù)據(jù) myclass.objects.all() 查詢帶字段名的所有條數(shù)數(shù)據(jù) myclass.objects.all().values() 查詢單挑數(shù)據(jù) myclass.objects.get(aa=’123’) #查詢aa字段中是123的這條數(shù)據(jù),如果是多條和沒有的時候會報錯,盡量結(jié)合try:except使用 查詢匹配條件的多條數(shù)據(jù) myclass.objects.filter(aa=’123’) #查詢aa字段值為123的所有數(shù)據(jù)條數(shù),括號的匹配條件可多個,以逗號分隔 模糊查詢 myclass.objects .filter(aa__contains=”1”) #查詢aa字段中值包含’1’的數(shù)據(jù),例如aa字段值為 123 154 這兩條都能匹配 根據(jù)字段內(nèi)容排序后展示數(shù)據(jù) myclass.objects.order_by(‘a(chǎn)a’) #根據(jù)aa字段的內(nèi)容進行數(shù)據(jù)排序,會根據(jù)字母和數(shù)字排序 根據(jù)字段內(nèi)容逆向排序后展示數(shù)據(jù),加一個負號 myclass.objects .order_by(‘-aa’ ) #根據(jù)aa字段的內(nèi)容進行逆向數(shù)據(jù)排序,會根據(jù)字母和數(shù)字排序 連鎖查詢,先過濾,過濾后進行逆向排序 myclass.objects.filter(aa=’123’) .order_by(“‐aa”) 限制數(shù)據(jù)條數(shù),相當于mysql limit myclass.objects.filter(aa=’123’)[0] #[0]顯示第一條 [0:2]會顯示前兩條 myclass.objects.filter(aa=’123’).order_by(“‐aa”)[0] #切片不支持負數(shù),這樣就數(shù)據(jù)序列倒過來的第一條,也就是最后一條數(shù)據(jù)
參考文獻: https://my.oschina.net/leeyd/blog/367688 https://docs.djangoPRoject.com/en/1.10/intro/tutorial02/ http://www.cnblogs.com/liujianzuo888/articles/5798658.html
新聞熱點
疑難解答