ORM執行原生SQL語句


# 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)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM