Django中使用原生Sql

2021-08-20 02:18:08 字數 1483 閱讀 5933

在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=)

使用raw:

book.objects.raw('select * from hello_book')

#使用 raw() 的 translations 引數來進行對映。這個引數是乙個對映查詢欄位名稱和模型欄位名稱的字典。

name_map =

book.objects.raw('select * from some_other_table', translations=name_map)

自定義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() #讀取所有

curr.execute("exec proc_getconflist %s, %s, %s, %s",('990003', none, none, none))

Django中使用原生SQL

使用extra 結果集修改器,一種提供額外查詢引數的機制 models.book.objects.filter publisher name 人民出版社 extra where price 50 models.book.objects.filter publisher name 人民出版社 pric...

在Django中使用原生sql

raw row方法 摻雜著原生sql和orm來執行的操作 res cookbook.objects.raw select id as nid from epos cookbook where id s params 1,print res.columns nid print type res 在se...

django中使用原生sql語句

row方法 摻雜著原生sql和orm來執行的操作 res cookbook.objects.raw select id as nid from epos cookbook where id s params 1 print res.columns nid print type res 在select...