Here is my model:
class Question(models.Model):
options = models.TextField()
Here is the serializer:
class QuestionSerializer(ModelSerializer):
class Meta:
model = Question
Here is the view:
class QuestionView(ListAPIView):
queryset = Question.objects.all()
renderer_classes = (JSONRenderer,)
serializer_class = QuestionSerializer
Inside the database, an available record looks like this:
id options
1 [u'opt1', u'opt2']
When the api is requested, here is the returned JSON:
{
"id": 1,
"options": "[u'opt1', u'opt2']"
}
My question is how to save a string in JSON format and retrieve it in JSON format without the unicode prefix? (I need to support unicode characters, so I cannot simply convert the data submitted by users to string)
Update: Here is one solution that I have found so far. Use django-jsonfield to define your field:
from jsonfield import JSONField
class Question(models.Model)
options = JSONField()
Then, define a custom serializer field:
from rest_framework import serializers
class JsonField(serializers.Field):
def to_representation(self, value):
return value
def to_internal_value(self, data):
return data
Use this field in a serializer:
class QuestionSerializer(ModelSerializer):
options = JsonField()
class Meta:
model = Question
Now if you try to store and then retrieve a record from the database, you should get a JSON formated string back without the unicode prefix.
Since django-jsonfield is looking for maintainers ATM, just in case it becomes obsolete, here are the versions I am using:
- Django 1.8.7
- django-jsonfield 1.0.3
- PostgresSQL 9.4.0.1