Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django REST framework: create JSON fragments from string

I want to store JSON fragments in TextField of my model with JSON:

class A(models.Model):
    name = models.CharField(max_length=200)
    people = models.TextField()

I have serializer class:

class ASerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = A
        fields = ('name', 'people')

How can I told Django REST Framework to treat people string like JSON, not like string. E.g. when people is [ {"name":"A", "surname":"B"}] I want have in JSON generated by Django REST framework

"people" : [ {"name":"A", "surname":"B"}]

and not

"people" : "[ {\"name\":\"A\", \"surname\":\"B\"}]"

Edit: I change ASerializer class and used JSONField from django-jsonfield and everything works. New code below, transform_people method serves to serialization and validate_people to deserialization:

class ASerializer(serializers.ModelSerializer):
    def transform_people(self, obj, value):
        if obj is None:
            return obj
        else:
            return obj.people

    def validate_people(self, attrs, source):
        return attrs

    class Meta:
        model = A
like image 239
pstrag Avatar asked Sep 30 '22 09:09

pstrag


2 Answers

Convert your response to json object

import json
## In this case lets say
response = [{"name":"A", "surname":"B"}]
data = json.dumps(response)
print data
like image 68
Ambarish Avatar answered Oct 16 '22 00:10

Ambarish


You could use serializers.JSONField

class ASerializer(serializers.HyperlinkedModelSerializer):
    people = serializers.JSONField()

    class Meta:
        model = A
        fields = ('name', 'people')
like image 27
JPG Avatar answered Oct 16 '22 00:10

JPG