1、執行自定義SQL方法
一、Executing custom SQL directly
直接執行自定義SQL,這種方式能夠徹底避免數據模型,而是直接執行原始的SQL語句。
二、Manager.raw()
執行原始查詢並返回模型實例
2、Executing custom SQL directly
Manager.raw() 遠遠不夠,可直接執行自定義SQL,directly execute UPDATE , INSERT , or DELETE queries.django.db.connection:表明默認的數據庫鏈接
django.db.transaction :表明默認數據庫事務(transaction)
用database connection調用 connection.cursor() 獲得一個遊標(cursor)對象。
而後調用 cursor.execute(sql, [params]) 執行SQL
cursor.fetchone() 或者 cursor.fetchall(): 返回結果行
若是執行修改操做,則調用 transaction.commit_unless_managed()來保證你的更改提交到數據庫。
def my_custom_sql():
from django.db import connection, transaction
cursor = connection.cursor()
# 數據修改操做——提交要求
cursor.execute("UPDATE bar SET foo = 1 WHERE baz = %s", [self.baz])
transaction.commit_unless_managed()
cursor.execute("UPDATE bar SET foo = 1 WHERE baz = %s", [self.baz])
transaction.commit_unless_managed()
# 數據檢索操做,不須要提交
cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz])
row = cursor.fetchone()
cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz])
row = cursor.fetchone()
return row
django.db.connections :針對使用多個數據庫
from django.db import connections
cursor = connections['my_db_alias'].cursor()
# Your code here...
transaction.commit_unless_managed(using='my_db_alias')
一般咱們不須要手動調用 transaction.commit_unless_managed( ),咱們能夠這樣作:
@commit_on_success
def my_custom_sql_view(request, value):
from django.db import connection, transaction
cursor = connection.cursor()
django.db.connections :針對使用多個數據庫
from django.db import connections
cursor = connections['my_db_alias'].cursor()
# Your code here...
transaction.commit_unless_managed(using='my_db_alias')
一般咱們不須要手動調用 transaction.commit_unless_managed( ),咱們能夠這樣作:
@commit_on_success
def my_custom_sql_view(request, value):
from django.db import connection, transaction
cursor = connection.cursor()
# Data modifying operation
cursor.execute("UPDATE bar SET foo = 1 WHERE baz = %s", [value])
cursor.execute("UPDATE bar SET foo = 1 WHERE baz = %s", [value])
# Since we modified data, mark the transaction as dirty
transaction.set_dirty()
transaction.set_dirty()
# Data retrieval operation. This doesn't dirty the transaction,
# so no call to set_dirty() is required.
cursor.execute("SELECT foo FROM bar WHERE baz = %s", [value])
row = cursor.fetchone()
# so no call to set_dirty() is required.
cursor.execute("SELECT foo FROM bar WHERE baz = %s", [value])
row = cursor.fetchone()
return render_to_response('template.html', {'row': row})
查看Django ORM執行的SQL語句 : connection.queries
查看Django ORM執行的SQL語句 : connection.queries
3、raw()方法
一、raw()用法
The raw() manager method can be used to perform raw SQL queries that return model instances:
Manager. raw ( raw_query , params=None , translations=None )
用法:
>>> for p in Person.objects.raw('SELECT * FROM Person LIMIT 2'):
... print p
John Smith
Jane Jones
注意,原始SQL裏的model,若是在 db_table 沒有定義,則使用app的名稱,後面下劃線 後面接模型類的名稱,如"Myblog_New";上面的例子,在定義類的時候已經這樣處理了:
Class New(models.Model):
......
......
#自定義表名
class Meta:
db_table = 'New'
Manager. raw ( raw_query , params=None , translations=None )
用法:
>>> for p in Person.objects.raw('SELECT * FROM Person LIMIT 2'):
... print p
John Smith
Jane Jones
注意,原始SQL裏的model,若是在 db_table 沒有定義,則使用app的名稱,後面下劃線 後面接模型類的名稱,如"Myblog_New";上面的例子,在定義類的時候已經這樣處理了:
Class New(models.Model):
......
......
#自定義表名
class Meta:
db_table = 'New'
二、查詢字段隱射到模型字段(Mapping query fields to model fields)
raw() automatically maps fields in the query to fields on the model.而且是經過名稱來匹配,這意味着咱們可使用SQL子句(clause)
>>> Person.objects.raw('''SELECT first AS first_name,
... last AS last_name,
... bd AS birth_date,
... pk as id,
... FROM some_other_table''')
返回一個RawQuerySet對象
>>> Person.objects.raw('''SELECT first AS first_name,
... last AS last_name,
... bd AS birth_date,
... pk as id,
... FROM some_other_table''')
返回一個RawQuerySet對象
三、索引查找(Index lookups)
first_person = Person.objects.raw('SELECT * from myapp_person')[0]
first_person = Person.objects.raw('SELECT * from myapp_person LIMIT 1')[0]
#然而,索引和切片不是在數據庫級別上執行(除LIMIT外)
first_person = Person.objects.raw('SELECT * from myapp_person LIMIT 1')[0]
#然而,索引和切片不是在數據庫級別上執行(除LIMIT外)
四、延遲模型字段(Deferring model fields)
Fields may also be left out(left out:忽視,不考慮;被遺忘),這意味着該字段的查詢將會被排除在根據須要時的加載。
>>> for p in Person.objects.raw('SELECT id, first_name FROM myapp_person'):
... print p.first_name, # 這將檢索到原始查詢
... print p.last_name # 這將檢索需求
...
John Smith
Jane Jones
這個例子其實檢索了三個字段,一個主鍵(必需)、一個原始SQL字段、一個需求字段。這裏主鍵字段不能省略,不然會出錯,以下:
>>> for p in Person.objects.raw('SELECT id, first_name FROM myapp_person'):
... print p.first_name, # 這將檢索到原始查詢
... print p.last_name # 這將檢索需求
...
John Smith
Jane Jones
這個例子其實檢索了三個字段,一個主鍵(必需)、一個原始SQL字段、一個需求字段。這裏主鍵字段不能省略,不然會出錯,以下:
五、傳遞參數(Passing parameters into raw() )
若是須要執行參數化查詢,您可使用params參數原始()
注意兩點:
注意兩點:
(1)、必須使用[參數],不然出錯:
(2)、這種方式不對:
Error:
>>> query = 'SELECT * FROM myapp_person WHERE last_name = %s' % lname
>>> Person.objects.raw(query)
(2)、這種方式不對:
Error:
>>> query = 'SELECT * FROM myapp_person WHERE last_name = %s' % lname
>>> Person.objects.raw(query)
轉載自:https://www.cnblogs.com/hello-/articles/9095444.html