django中使用原生sql


在Django中使用原生Sql主要有以下幾種方式:
一:extra:結果集修改器,一種提供額外查詢參數的機制
二:raw:執行原始sql並返回模型實例
三:直接執行自定義Sql
(
這種方式完全不依賴model,前兩種還是要依賴於model
)
 
實例:
使用extra:
1:Book.objects.filter(publisher__name='廣東人員出版社').extra(where=['price>50'])
Book.objects.filter(publisher__name='廣東人員出版社',price__gt=50)
 
2:Book.objects.extra(select={'count':'select count(*) from hello_Book'})
 
使用raw:
Book.objects.raw('select * from hello_Book')
 
自定義sql:
Book.objects.raw("insert into hello_author(name) values('測試')")
rawQuerySet為惰性查詢,只有在使用時生會真正執行
 
執行自定義sql:
from django.db import connection
cursor=connection.cursor()
#插入操作
cursor.execute("insert into hello_author(name) values('郭敬明')")
#更新操作
cursor.execute('update hello_author set name='abc' where name='bcd'')
#刪除操作
cursor.execute('delete from hello_author where name='abc'')
#查詢操作
cursor.execute('select * from hello_author')
raw=cursor.fetchone() #返回結果行游標直讀向前,讀取一條
cursor.fetchall() #讀取所有


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM