Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django-rest-framework: How Do I Serialize a Field That Already Contains JSON?

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...

like image 306
Jason Champion Avatar asked Mar 03 '14 20:03

Jason Champion


People also ask

What is the difference between ModelSerializer and HyperlinkedModelSerializer?

The HyperlinkedModelSerializer class is similar to the ModelSerializer class except that it uses hyperlinks to represent relationships, rather than primary keys. By default the serializer will include a url field instead of a primary key field.

How do you pass extra context data to Serializers in Django REST framework?

In function-based views, we can pass extra context to serializer with “context” parameter with a dictionary. To access the extra context data inside the serializer we can simply access it with “self. context”. From example, to get “exclude_email_list” we just used code 'exclude_email_list = self.

Is serialization necessary in Django?

It is not necessary to use a serializer. You can do what you would like to achieve in a view. However, serializers help you a lot. If you don't want to use serializer, you can inherit APIView at a function-based-view.

What is serialization in Django REST framework?

Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.


1 Answers

I solved this another way:

1: use a JSON-Field for the JSON content (django-jsonfield or django-json-field should be fine). These then will to loads/dumps as needed

2: in my serializer, use the transform-method to prevent the data added as string to the response

class MyModelSerializer(serializers.ModelSerializer):
    def transform_myjsonfield(self, obj, value):
        return obj.myjsonfield

    class Meta:
        model = MyModel

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.

like image 53
Denis Cornehl Avatar answered Sep 17 '22 23:09

Denis Cornehl