Django中执行原生SQL语句【新编辑】

时间:2021-11-15 09:14:20

参考我的个人博客

这部分迁移到了个人博客中:Django中执行原生SQL语句

这里需要补充一下,还有一个extra方法:

ret = models.Student.objects.all().extra(where=['id > %s'], params=[''], 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""", [])
row = cursor.fetchone() # fetchall()/fetchmany(..)

选择数据库

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

~~