django执行数据库查询之后返回的结果集如何转json

django执行sql语句后得到的返回结果是一个结果集,直接把结果转json返回给前端会报错,需要先遍历转字典在转json,特别注意model_to_dict()只会将结果集的第一条数据转字典,如果你是根据指定条件查一条数据返回的,直接用model_to_dict()没问题,如果执行的是all()或filter()到多条或全部的数据,这个时候去model_to_dict()这个集合就不行了,那么先遍历这个集合在转字典,然后转json就ok了

dic = {}
res = models.tables.objects.all().order_by('-id')
L = []
b = model_to_dict(res)
L.append(b)
dic['code'] = '1'
dic['message'] = ''
dic['result'] = L
return HttpResponse(json.dumps(dic, ensure_ascii=False))

order_by('-id'):是将结果集根据ID倒序排序

猜你喜欢

转载自blog.csdn.net/xopqaaa/article/details/88242524