陳娜 付沛
摘要:Django通過Manager(模型管理器)提供數據庫訪問接口。默認情況下,Django為每個模型添加一個名為objects的管理器,調用objects的各種方法?可完成相關的數據庫操作;也可以用模型管理器的raw()方法執(zhí)行原始SQL查詢并返回模型示例;或者不使用模型直接執(zhí)行原始SQL。本文介紹3種方法,可根據自身情況選擇一種方法完成數據庫操作。
在django中我們只需要操作類或者對象,ORM它系統(tǒng)幫你根據類和對象來操作數據庫
類--à數據表?對象?---〉數據行?屬性—〉?字段
首先創(chuàng)建項目mydjango
1、?創(chuàng)建book?應用
2、?在settings.py文件中加入book應用
3、?打開models.py定義表的結構
class?faqsdata(models.Model):
question?=?models.CharField(max_length=20,?blank=True)
answer?=?models.CharField(max_length=20,?blank=True)
4、使用命令生成遷移文件(系統(tǒng)幫你生成的sql語句)
python?manage.py?makemigrations
5、使用命令?運行?遷移文件(相當于執(zhí)行sql命令)
python?manage.py?migrate
6、打開終端輸入以下命令進入當前項目的Python交互環(huán)境
python?manage.py?shell
7、導入模型類
from?book.models?import?;faqsdata
一、使用默認管理器objects
Django通過模型對象的默認管理器objects提供了多種獲取數據的方法
(1)create方法創(chuàng)建模型的對象,并將數據保存進數據庫
>>>?ds=faqsdata.objects.create(question='test',answer='bbb')
>>>?ds=faqsdata.objects.create(question='test434',answer='aaa')
(2)all方法獲取所有數據行,相當于sql中的select?*?from?****
>>>?ds=faqsdata.objects.all()
>>>?for?a?in?ds:
...?print(a.id,a.question,a.answer)
...
1?test?bbb
2?test4334?aaa
(3)get、filter、update方法過濾出符合條件的行進行更新
1更新單行
>>>?ds=faqsdata.objects.get(id="1")
>>>?print(ds.id,ds.question,ds.answer)
1?test?bbb
>>>?ds.question="yyyyyyyy"
>>>?d.save()
>>>?print(ds.id,ds.question,ds.answer)
1?yyyyyyyy?bbb
2更新多行
>>>?ds=faqsdata.objects.filter(id__lte="9")
>>>?ds.update(answer='bbbbbb')
4
>>>?ds=faqsdata.objects.update(answer='ppppp')?全表更新
>>>
(4)filter、delete方法過濾出符合條件的行進行刪除
>>>?faqsdata.objects.filter(id__gt=9).delete()?get刪除單行
(3,?{'book.faqsdata':?3})
二、用模型管理器raw()方法執(zhí)行原始SQL
>>>?ds=scores.objects.raw("select?*?from?book_scores?where?yw<%s",[50])
>>>?for?a?in?ds:
...?print(a.id,a.kh,a.xm,a.yw,a.sx,a.bj)
...
>>>?ds=scores.objects.raw("update?book_scores?set?yw=100?where?id=3")
>>>?ds.query._execute_query()
>>>d=scores.objects.raw("insert?into?book_scores(kh,xm,yw,sx,bj)?values?('10110199','fdsaf',11,22,'class1')")
>>>?d.query._execute_query()
>>>?d=scores.objects.raw("delete?from?book_scores?where?id=63")
>>>?d.query._execute_query()
三、不使用模型訪問數據庫
也可以不使用模型管理器直接訪問數據庫,使用游標,但是有SQL注入風險,基本步驟如下:
調用django.db.connection.cursor()方法獲得一個游標對象。django.db.connection對象代表默認數據庫連接。
調用游標對象的execute(sql)方法執(zhí)行SQL命令。
調用游標對象的fetchall()或fetchone()方法返回數據。
>>>?from?django.db?import?connection
>>>?cursor=connection.cursor()
>>>?cursor.execute("select?*?from?book_scores?where?id<7")
>>>?for?a?in?cursor.fetchall():
...?print(a[0],a[1],a[2])
...
>>>a=cursor.execute("insert?into?book_scores(kh,xm,yw,sx,bj)?values?('10110199','fdsaf',11,22,'class1')")
>>>?a=cursor.execute("update?book_scores?set?yw=100?where?id=10")
>>>?a=cursor.execute("delete?from?book_scores?where?id=10")