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
Convert your response to json object
import json
## In this case lets say
response = [{"name":"A", "surname":"B"}]
data = json.dumps(response)
print data
You could use serializers.JSONField
class ASerializer(serializers.HyperlinkedModelSerializer):
people = serializers.JSONField()
class Meta:
model = A
fields = ('name', 'people')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With