Django框架Object of type ‘QuerySet’ is not JSON serializable

报错信息如下

Object of type 'QuerySet' is not JSON serializable

报错代码

1
2
3
4
5
6
def queryinfo(request):
    mydata=news.objects.all()
    data = {
        'list': mydata
    }
    return HttpResponse(json.dumps(data), content_type='application/json')

报错原因

queryset没有序列化

解决方案

1
2
3
4
5
6
7
def queryinfo(request):
    mydata=news.objects.all()
    newsdata= serializers.serialize("json", mydata)
    data = {
        'list': newsdata
    }
    return HttpResponse(json.dumps(data), content_type='application/json')

运行成功效果图