1、manager.
raw
(raw_query, params=none, translations=none)
... print(p)
john smith
jane jones
這個方法接受乙個原始的sql查詢,執行它,並返回乙個django.db.models.query。rawqueryset例項。這個rawqueryset例項可以像普通的queryset一樣遍歷,以提供物件例項。
(1)字段匹配
>>> person.objects.raw('''select first as first_name,
... last as last_name,
... bd as birth_date,
... pk as id,
... from some_other_table''')
>>> name_map =
>>> person.objects.raw('select * from some_other_table', translations=name_map)
(2)即使沒有顯示表明查詢字段,也可以獲取
... print(p.first_name, # this will be retrieved by the original query
... p.last_name) # this will be retrieved on demand
...john smith
jane jones
(3)執行帶引數sql
字串用%s佔位符
字典用%(key)s佔位符
>>> lname = 'doe'
(4)嚴禁使用字串拼接
>>> person.objects.raw(query)
(4)引數不能用引號包裹
2、通過connection.cursor()執行sql
物件django.db.connection表示預設的資料庫連線。要使用資料庫連線,請呼叫connection.cursor()來獲得乙個游標物件。然後呼叫cursor.execute(sql, [params])方法以執行sql
cursor.fetchone()或cursor.fetchall()以返回結果行。
from django.db import connection
def my_custom_sql(self):
with connection.cursor() as cursor:
cursor.execute("update bar set foo = 1 where baz = %s", [self.baz])
cursor.execute("select foo from bar where baz = %s", [self.baz])
row = cursor.fetchone()
return row
(1)傳遞百分比引數需要寫兩個百分號
cursor.execute("select foo from bar where baz = '30%%' and id = %s", [self.id])
(2)cursor執行不會返回列名
用字典或命名元組
def dictfetchall(cursor):
"return all rows from a cursor as a dict"
columns = [col[0] for col in cursor.description]
return [
dict(zip(columns, row))
for row in cursor.fetchall()
]
from collections import namedtuple
def namedtuplefetchall(cursor):
"return all rows from a cursor as a namedtuple"
desc = cursor.description
nt_result = namedtuple('result', [col[0] for col in desc])
return [nt_result(*row) for row in cursor.fetchall()]
>>> cursor.execute("select id, parent_id from test limit 2");
>>> dictfetchall(cursor)
[, ]
Django執行原生SQL語句
msg show successfully error tag 0 用connection庫 和原生的sql語句讀資料庫,如下 from django.db import connection 匯入connection sql str select from book str型別的原生sql語句 c...
django使用raw 執行sql語句多表查詢
python3.7 django2.2.16 mysql5.7 資料庫表 product 產品表 model replace 產品型號替換表 兩個表並沒有外來鍵關聯關係,只是通過乙個product unique sign去關聯 product product id product name prod...
Django中直接執行SQL語句
歡迎加入python學習 667279387 今天在django views.py看到同事寫的 裡面有段關於資料庫查詢的語句。因為涉及多個表的查詢,所以django 的models的查詢無法滿足需求,所以直接執行了sql語句。他是按照下面的方法實現的。try connection mysqldb.c...