1.使用extra方法
解釋:結(jié)果集修改器,一種提供額外查詢參數(shù)的機制
說明:依賴model模型
用在where后:
News.objects.filter(id=1).extra(where=["title='生命的意義'"])
用在select后
News.objects.filter(id=1).extra(select={"count":"select count(*) from book"})
2.使用raw方法
解釋:執(zhí)行原始sql并返回模型
說明:依賴model多用于查詢
用法:
student= Book.objects.raw("select * from student")
for item in student:
print(item.name)
3.執(zhí)行自定義SQL
解釋:利用游標(biāo)執(zhí)行
導(dǎo)入:from django.db import connection
說明:不依賴model
用法:
from django.db import connection
cursor = connection.cursor()
#插入
cursor.execute("insert into student(name) values('小強')")
#更新
cursor.execute("updatestudent set name='小剛' where id=1")
#刪除
cursor.execute("delete from student where name='小王'")
#查詢
cursor.execute("select * from student")
#返回一行
raw = cursor.fetchone()
print(raw)
# #返回所有
# cursor.fetchall()