Django中執行原生SQL語句【新編輯】

參考個人我的博客

這部分遷移到了我的博客中:Django中執行原生SQL語句數據庫

這裏須要補充一下,還有一個extra方法:django

ret = models.Student.objects.all().extra(where=['id > %s'], params=['1'], order_by=['-id']) # print(ret) # for i in ret: # print(i)

 小結

extra

Entry.objects.extra(select={'new_id': "select col from sometable where othercol > %s"}, select_params=(1,))
Entry.objects.extra(where=['headline=%s'], params=['Lennon'])
Entry.objects.extra(where=["foo='a' OR bar = 'a'", "baz = 'a'"])
Entry.objects.extra(select={'new_id': "select id from tb where id > %s"}, select_params=(1,), order_by=['-nid'])

raw

# 執行原生SQL
models.UserInfo.objects.raw('select * from userinfo')

# 若是SQL是其餘表時,必須將名字設置爲當前UserInfo對象的主鍵列名
models.UserInfo.objects.raw('select id as nid from 其餘表')

# 爲原生SQL設置參數
models.UserInfo.objects.raw('select id as nid from userinfo where nid>%s', params=[12,])

name_map = {'first': 'first_name', 'last': 'last_name', 'bd': 'birth_date', 'pk': 'id'}
Person.objects.raw('SELECT * FROM some_other_table', translations=name_map)

直接執行原生SQL

from django.db import connection, connections
cursor = connection.cursor()  # cursor = connections['default'].cursor()
cursor.execute("""SELECT * from auth_user where id = %s""", [1])
row = cursor.fetchone() # fetchall()/fetchmany(..)

選擇數據庫 

queryset = models.Course.objects.using('default').all()

~~fetch

相關文章
相關標籤/搜索