Orm多條件查詢
>>> query_text = "123"
>>> Product.objects.filter(Q(id__icontains=query_text) | Q(name__icontains=query_text))
Django提供兩種方式執行(performing)原始的SQL查詢:
1、Manager.raw():執行原始查詢並返回模型實例
>>> Manager.raw(raw_query, params=None, translations=None)
>>> forexample:person.objects.raw("select id,…… from person_table")
#不要漏了主鍵(id)否則會出錯:InvalidQuery: Raw query must include the primary key
1.1傳遞參數(Passing parameters into raw())
>>> name = 'Doe'
>>> Person.objects.raw('SELECT * FROM myapp_person WHERE last_name = %s', [name])
2、Executing custom SQL directly:直接執行自定義SQL,這種方式可以完全避免數據模型,而是直接執行原始的SQL語句。
具體流程:
導入 form django.db import connection,transaction
django.db.connection:代表默認的數據庫連接
django.db.transaction:代表默認數據庫事務(transaction)
connection.cursor(): 獲得一個遊標(cursor)對象
cursor.execute(sql, [params]):執行SQL
cursor.fetchone() 或者 cursor.fetchall():返回結果行
如果執行修改操作,則調用transaction.commit_unless_managed()來保證你的更改提交到數據庫。
示例:
sql = "select * from table where var like '%%fff%%'"
cursor = connection.cursor()
cursor.execute(sql)
raw = cursor.fetchall() ##結果
使用like的時候,如果報錯信息爲:’Cursor’ object has no attribute ‘_last_executed
就用兩個%