Django 提示:Object of type ‘QuerySet‘ is not JSON serializable
Posted 在奋斗的大道
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django 提示:Object of type ‘QuerySet‘ is not JSON serializable相关的知识,希望对你有一定的参考价值。
错误信息:
Traceback (most recent call last):
File "C:\\python3\\lib\\site-packages\\django\\core\\handlers\\exception.py", line 47, in inner
response = get_response(request)
File "C:\\python3\\lib\\site-packages\\django\\core\\handlers\\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "F:\\python_workspace\\MyDjango\\userSystem\\views.py", line 12, in select
return response_success(message='后台响应成功', data_list=books)
File "F:\\python_workspace\\MyDjango\\userSystem\\views.py", line 20, in response_success
'dataList': data_list#返回对象数组
File "C:\\python3\\lib\\json\\__init__.py", line 231, in dumps
return _default_encoder.encode(obj)
File "C:\\python3\\lib\\json\\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "C:\\python3\\lib\\json\\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "C:\\python3\\lib\\json\\encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type QuerySet is not JSON serializable
大致意思:查询对象集合没有进行JSON 序列化
解决办法:
1:引入django 序列化类
from django.core import serializers
2:将查询结果序列化,并输出
return response_success(message='后台响应成功', data_list=serializers.serialize("json", books))
Python 完整代码:
import json
from django.shortcuts import render
from userSystem.models import Book
from django.http import HttpResponse
from django.core import serializers
# Create your views here.
def select(request):
books = Book.objects.all()
for i in range(len(books)):
print("主键:%s 值:%s" % (i + 1, books[i]))
return response_success(message='后台响应成功', data_list=serializers.serialize("json", books))
def response_success(message, data=None, data_list=[]):
return HttpResponse(json.dumps({
'code': 200,#code由前后端配合指定
'message': message,#提示信息
'data': data,#返回单个对象
'dataList': data_list#返回对象数组
}), 'application/json')
以上是关于Django 提示:Object of type ‘QuerySet‘ is not JSON serializable的主要内容,如果未能解决你的问题,请参考以下文章
flask查询User,返回对象列表,提示ypeError: Object of type ‘bytes‘ is not JSON serializable解决办法
RF之TypeError: Object of type 'bytes' is not JSON serializable
TypeError: Object of type datetime is not JSON serializable问题解决
TypeError: Object of type datetime is not JSON serializable问题解决
Unable to cast object of type 'System.Int32' to type 'System.String'.
Could not find method implementation() for arguments [directory ‘libs‘] on object of type org.gradle