# 1.connection
from django.db import connection, connections cursor = connection.cursor() # cursor = connections['default'].cursor() cursor.execute("""SELECT * from auth_user where id = %s""", [1]) ret = cursor.fetchone()
有點像pymysql
2.extra
extra(select=None, where=None, params=None, tables=None, order_by=None, select_params=None)
select選擇,參數是字典的形式
time_type = models.Article.objects.filter(user=user_obj) time_list = time_type.extra( select={"new_time": "date_format(create_time, '%%Y-%%m')"} ).values("new_time").annotate(time_count=Count("nid")).values("new_time", "time_count")
3.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)