Django Model 10.原生sql语句

模型类

还是上节课的Clazz1和Student4
重写返回值,显示姓名和成绩

def __str__(self):
   return 'Student4:%s %s' % (self.sname, self.score)

用sql的select语言

raw原生全查询

raw查询只适合select all 全选

from stu.models import *
stus = Student4.objects.raw('select * from stu_student4')
print(stus)
<RawQuerySet: select * from stu_student4>
for s in stus:
	print(s)
#结果
Student4:zhangsan 88
Student4:zhangsan 88
Student4:lisi 99
Student4:wangwu 66
Student4:zhaoliu 77

cursor游标部分查询

如果只想部分字段,raw查询因不包含主键会报错

stus = Student4.objects.raw('select sname from stu_student4')
Raw query must include the primary key

需要用cursor游标,指针指向表,稍微有点繁琐

from django.db import connection
cur = connection.cursor()
cur.execute('select sname,score from stu_student4')
cs = cur.fetchall()
print(cs)
for c in cs:
	print(c)
cur.close()
#结果
(('zhangsan', 88), 
('zhangsan', 88), 
('lisi', 99), 
('wangwu', 66), 
('zhaoliu', 77))
('zhangsan', 88)
('zhangsan', 88)
('lisi', 99)
('wangwu', 66)
('zhaoliu', 77)

cursor不仅支持局部字段,也可以select *选择全部
对于只包含一个结果的,可以把fetchall改为fetchone

封装方法

由于raw查询有局限,我们把cursor查询进行封装,其实这里虽然繁琐,但只有sql语句不一样
with方法可以自动关闭,不需要再写close

def test(sql):
	from django.db import connection
	with connection.cursor() as c:
		c.execute(sql)
		for info in c.fetchall():
			print(info)
test('select * from stu_clazz1')
#结果
(1, 'B201Python班')
(2, 'B202Python班')
(3, 'B203Python班')

写在背后:
pycharm过期了,装了2019.1居然跟python3.8不匹配

发布了31 篇原创文章 · 获赞 8 · 访问量 1003
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 创作都市 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览