TypeError: In order to allow non-dict objects to be serialized set the safe解决方法

前端之家收集整理的这篇文章主要介绍了TypeError: In order to allow non-dict objects to be serialized set the safe解决方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

在开发中使用JsonResponse返回数据遇到错误

TypeError: In order to allow non-dict objects to be serialized set the safe

views.py代码示例

def userProfile(request):
    posts = User.objects.order_by('id')[:10].reverse()
    return JsonResponse(posts)

JsonResponse源码:

class JsonResponse(HttpResponse):
    """
    An HTTP response class that consumes data to be serialized to JSON.

    :param data: Data to be dumped into json. By default only ``dict`` objects
      are allowed to be passed due to a security flaw before EcmaScript 5. See
      the ``safe`` parameter for more information.
    :param encoder: Should be a json encoder class. Defaults to
      ``django.core.serializers.json.DjangoJSONEncoder``.
    :param safe: Controls if only ``dict`` objects may be serialized. Defaults
      to ``True``.
    :param json_dumps_params: A dictionary of kwargs passed to json.dumps().
    """

    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().__init__(content=data, **kwargs)

根据源码得知,是因为传入的data参数不是一个字典导致的错误

解决方法

def userProfile(request):
    posts = User.objects.order_by('id')[:10].reverse()
    return JsonResponse(posts, safe=False)

文档网址:https://docs.djangoproject.com/zh-hans/2.2/_modules/django/http/response/

猜你在找的Django相关文章