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)
原文地址:https://www.cnblogs.com/wt7018/p/11332481.html