Django 调试时提示: In order to allow non-dict objects to be serialized

isinstance()函数:

该函数判断一个对象是否是已知的类型,类似于type()

isinstance()会认为子类是一种父类类型,考虑了继承关系,而type()不会认为子类是一种父类类型,不考虑继承关系。

isinstance(object,classinfo)object是实例对象,classinfo是直接或间接类名,基本类型或者由他们组成的元组。

return JsonResponse(result)变更为return JsonResponse(result,safe=False)
原因看源码:

def __init__(self, data, encoder=DjangoJSONEncoder, safe=True,
             json_dumps_params=None, **kwargs):
    if safe and not isinstance(data, dict):
        raise TypeError(
            'In order to allow non-dict objects to be serialized set the '
            'safe parameter to False.'
        )
  
  if json_dumps_params is None:
        json_dumps_params = {}
    kwargs.setdefault('content_type', 'application/json')
    data = json.dumps(data, cls=encoder, **json_dumps_params)
    super(JsonResponse, self).__init__(content=data, **kwargs)

if safe and not isinstance(data, dict):如果safe=True 传入的数据类型不是dict,那么条件就成立,抛出异常

posted @ 2019-12-01 17:40  醉醺醺的  阅读(929)  评论(0编辑  收藏  举报