ORM执行原生SQL语句

2023-05-16编程技术300552

# 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=[,]) name_map = {'first': 'first_name', 'last': 'last_name', 'bd': 'birth_date', 'pk': 'id'}
Person.objects.raw('SELECT * FROM some_other_table', translations=name_map)

ORM执行原生SQL语句的相关教程结束。

本文地址:https://www.ufcn.cn/tutorials/2643867.html

如非特殊说明,本站内容均来自于网友自主分享,概不代表本站观点,如有任何问题我们都将在收到反馈后的第一时间进行处理!