I am pretty new to the django-rest-framework, so could use some help.
I have an object with a TextField that is a string containing JSON.
I'm using django-rest-framework to serialize the whole object as JSON. However, this one string that is already JSON gets serialized as an encoded string containing the JSON rather than the JSON itself.
How can I tell the serializer to send this field as-is rather than trying to transform this string to JSON? Is there some sort of "ignore" decorator or override I can use? Or can I pre-parse this JSON before serializing?
This is the difference between having:
{"data": data}
and
{"data": "data"}
The latter being more of a nuisance to use on the client side...
You can simply decode the json into python object:
Once you serialize your object, replace this field with the decoded object:
I solved this another way:
1: use a JSON-Field for the JSON content (
django-jsonfield
ordjango-json-field
should be fine). These then will to loads/dumps as needed2: in my serializer, use the transform-method to prevent the data added as string to the response
If you need write-access, you only have to add a method
validate_myjsonfield
which converts back.(of course, this could be also done with a custom DRF serializer field.
Here is what works for me on,
djangorestframework==3.9.1
:I thought there would be an easier way to do this, but by changing the behaviour of
to_representation
, I can convert my text fields to JSON. For reference, here is mymodels.py
:Hope that helps. If you use a
JSONField
that is supported by Postgres, I'm sure you won't need to do this. I'm using a TextField to save my JSON here. I thought that specifying the field type asserializers.JSONField
on the serializer would be enough but its not the case.