简体   繁体   中英

Custom encoder ignored by django JsonResponse

I am building an app using Django Rest Framework (Versions: django 3.1, djangorestframework 3.11.1, python 3.7)

I want to override the encoder used in JsonResponse.

An oversimplification of my problem:

from django.http import JsonResponse
from django.core.serializers.json import DjangoJSONEncoder

class CustomEncoder(DjangoJSONEncoder):
    def default(self, o):
        return o + 10

response = JsonResponse({"data": 1}, encoder=CustomEncoder)

What I expect from response.getvalue() is '{"data": 11}' but instead I get '{"data": 1}' .

What am I doing wrong?

because DjangoJSONEncoder use for

JSONEncoder subclass that knows how to encode date/time, decimal types, and
UUIDs.

you must pass value like date/time, decimal types, or UUIDs for your method override default be called.

Try change to

class CustomEncoder(DjangoJSONEncoder):
    def default(self, o):
        return int(o) + 10

response = JsonResponse({"data": Decimal(1)}, encoder=CustomEncoder)

it will return {"data": 11}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM