TypeError:对象在DJango 1.8 Python 3.4中不是JSON可序列化的 [英] TypeError: object is not JSON serializable in DJango 1.8 Python 3.4

查看:89
本文介绍了TypeError:对象在DJango 1.8 Python 3.4中不是JSON可序列化的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用DJango 1.8和Python 3.4

I'm using DJango 1.8 and Python 3.4

运行以下视图时,Django抛出类型错误-对象不可JSON序列化

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

Views.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")

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

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

TypeError: YellowBased: YelloBased object is not JSON serializable

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

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.

Models.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和YellowStats表在mysql中仅包含2 * 2行 有人可以帮我找出这个问题吗?

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

推荐答案

您必须序列化student对象列表,请尝试以下操作:

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

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)

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

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

JsonResponse也可以自行完成操作,因此无需将其包装在HttpResponse中.

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

检查文档以进行更多自定义: https://docs.djangoproject.com/zh-CN/1.8/topics/serialization/

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

希望这会有所帮助!

这篇关于TypeError:对象在DJango 1.8 Python 3.4中不是JSON可序列化的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆