如题所说,很操蛋的是,搞了这么久django,居然被折腾这么久,老师一直也没讲清,今天特来总结为以后留作笔记
def studentsinfo(request): stus = Students.objects.all().get(pk=1) print(stus) print(type(stus)) a = Students.objects.all() print(a) print(type(a)) b = Students.objects.all().values('sname') print(b) print(type(b)) c = Students.objects.all().values_list() print(c) print(type(c)) # list = [] # for stu in stus: # print(stu) # list.append([stu.sname, stu.sage]) # print(type(stu)) return JsonResponse({'data': list})薛延美
<class 'myApp.models.Students'>
<QuerySet [<Students: 薛延美>, <Students: 陆彦旭>, <Students: 范育宾>, <Students: 向芳>, <Students: 阳亚霞>, <Students: 孔玉>, <Students: 孟林>, <Students: 孙雨>, <Students: 郝路杰>, <Students: 夏明宇>, <Students: 王子衡>, <Students: 韩俊>, <Students: 申宝静>, <Students: 孙狮勤>, <Students: 李嘉熙>, <Students: 许明宾>, <Students: 陈俊伟>, <Students: 何琪龙>, <Students: 武含>, <Students: 田宝迎>, '...(remaining elements truncated)...']>
<class 'django.db.models.query.QuerySet'>
<QuerySet [{'sname': '薛延美'}, {'sname': '陆彦旭'}, {'sname': '范育宾'}, {'sname': '向芳'}, {'sname': '阳亚霞'}, {'sname': '孔玉'}, {'sname': '孟林'}, {'sname': '孙雨'}, {'sname': '郝路杰'}, {'sname': '夏明宇'}, {'sname': '王子衡'}, {'sname': '韩俊'}, {'sname': '申宝静'}, {'sname': '孙狮勤'}, {'sname': '李嘉熙'}, {'sname': '许明宾'}, {'sname': '陈俊伟'}, {'sname': '何琪龙'}, {'sname': '武含'}, {'sname': '田宝迎'}, '...(remaining elements truncated)...']>
<class 'django.db.models.query.QuerySet'>
<QuerySet [(1, '薛延美', False, 20, '我叫薛延美', False, 4), (2, '陆彦旭', True, 30, '我叫陆彦旭', False, 4), (3, '范育宾', True, 40, '我叫范育宾', False, 4), (4, '向芳', False, 18, '我叫向芳', False, 4), (5, '阳亚霞', False, 16, '我叫阳亚霞', False, 4), (6, '孔玉', True, 50, '我叫孔玉', False, 4), (7, '孟林', True, 60, '我叫孟林', False, 3), (8, '孙雨', False, 70, '我叫孙雨', False, 3), (9, '郝路杰', True, 33, '我叫郝路杰', False, 3), (10, '夏明宇', True, 34, '我叫夏明宇', False, 3), (11, '王子衡', False, 28, '我叫王子衡', False, 3), (12, '韩俊', True, 4, '我叫韩俊', False, 2), (13, '申宝静', False, 6, '我叫申宝静', False, 2), (14, '孙狮勤', True, 20, '我叫孙狮勤', False, 2), (15, '李嘉熙', True, 10, '我叫李嘉熙', False, 2), (16, '许明宾', True, 54, '我叫许明宾', False, 2), (17, '陈俊伟', True, 45, '我叫陈俊伟', False, 3), (18, '何琪龙', True, 66, '我叫何琪龙', False, 4), (19, '武含', True, 23, '我叫武含', False, 3), (20, '田宝迎', False, 44, '我叫田宝迎', False, 2), '...(remaining elements truncated)...']>
<class 'django.db.models.query.QuerySet'>
下面为运行结果
get和filter的区别
get 返回值是一个定义的model对象,返回一个,多个报错
filter 返回值是一个新的QuerySet对象列表,可以返回对个对象
另外 get_list是获取参数里面的,如GET.get和GET.get_list,别记混了
def studentsinfo(request): stus = Students.objects.all().get(pk=1) print(stus) print(type(stus)) b = Students.objects.all().first() print(b) print(type(b)) a = Students.objects.all().filter(pk=1) print(a) print(type(a))
<class 'myApp.models.Students'>
薛延美
<class 'myApp.models.Students'>
<QuerySet [<Students: 薛延美>]>
<class 'django.db.models.query.QuerySet'>
输出结果证实first()和get(pk=1)是一样的,但filter仍然是一个列表