微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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 @R_352_4045@ion.
    :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/

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐