类型错误:对象在 DJango 1.8 Python 3.4 中不是 JSON 可序列化的

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30953615/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:13:33  来源:igfitidea点击:

TypeError: object is not JSON serializable in DJango 1.8 Python 3.4

pythonjsondjangopython-3.xserialization

提问by user3128771

I'm using DJango 1.8 and Python 3.4

我正在使用 DJango 1.8 和 Python 3.4

When the below view is being ran, Django throws Type Error - Object is not JSON Serializable

当运行下面的视图时,Django 抛出类型错误 - 对象不是 JSON Serializable

Views.py

视图.py

from django.http import HttpRequest,HttpResponse
from django.http import JsonResponse
from json import dumps

def get_stats(request):
    if request.method == "POST":
        srch_dropV = request.POST['srch_dropAJ']
    else:
        srch_dropV = ''
    if(srch_dropV == 'Green'):
        students = GreenBased.objects.all()
    if(srch_dropV == 'Yellow'):
        students = YellowBased.objects.all()
    response_data = {}
    try:
        response_data['result'] = 'Success'
        response_data['message'] = list(students)
    except:
        response_data['result'] = 'Ouch!'
        response_data['message'] = 'Script has not ran correctly'
    return HttpResponse(JsonResponse(response_data), content_type="application/json")

I'm trying to read couple of rows from mysql database and display it on the html file, I'm facing below error message when above view is being ran

我正在尝试从 mysql 数据库中读取几行并将其显示在 html 文件中,当运行上述视图时,我正面临以下错误消息

TypeError: YellowBased: YelloBased object is not JSON serializable

In HTML Page, I have a drop down list.. based on the option that is selected, my Ajax would return me the records that were fetched from mysql table.

在 HTML 页面中,我有一个下拉列表……根据选择的选项,我的 Ajax 会返回从 mysql 表中获取的记录。

Models.py

模型.py

class GreenBased(models.Model):
    NumOfStudents = models.CharField(max_length=300,blank=True)
    Green = models.CharField(max_length=300,blank=True)
    class Meta:
        managed = False
        db_table = "GreenStats"

class YelloBased(models.Model):
    NumOfStudents = models.CharField(max_length=300,blank=True)
    Yellow = models.CharField(max_length=300,blank=True)
    class Meta:
        managed = False
        db_table = "YellowStats"

GreenStats and YellowStats tables contains only 2*2 rows in mysql Can someone please help me to identify this issue ?

GreenStats 和 YellowStats 表在 mysql 中只包含 2*2 行有人可以帮我找出这个问题吗?

采纳答案by HassenPy

You have to serialize your studentobjects list, try something like this:

你必须序列化你的student对象列表,试试这样的:

from django.http import HttpRequest,HttpResponse
from django.http import JsonResponse
from json import dumps
from django.core import serializers


def get_stats(request):
    if request.method == "POST":
        srch_dropV = request.POST['srch_dropAJ']
    else:
        srch_dropV = ''
    if(srch_dropV == 'Green'):
        students = GreenBased.objects.all()
    if(srch_dropV == 'Yellow'):
        students = YellowBased.objects.all()
    response_data = {}
    try:
        response_data['result'] = 'Success'
        response_data['message'] = serializers.serialize('json', students)
    except:
        response_data['result'] = 'Ouch!'
        response_data['message'] = 'Script has not ran correctly'
    return JsonResponse(response_data)

Notice the line change in :
response_data['message'] = serializers.serialize('json', students)

注意 中的行更改:
response_data['message'] = serializers.serialize('json', students)

Also JsonResponsedoes the trick on its own, so no need to wrap it in a HttpResponse.

JsonResponse可以自行解决问题,因此无需将其包装在HttpResponse.

check the docs for more customization: https://docs.djangoproject.com/en/1.8/topics/serialization/

检查文档以获取更多自定义:https: //docs.djangoproject.com/en/1.8/topics/serialization/

Hope this helps!

希望这可以帮助!