0

I've used JSONfield in my serilizer and as the user in the thread store json as dict points out, DRF with Mysql stores JSONfield as a dict

However I would rather store it as JSON {"tags":{"data":"test"}} instead of the default behavior of storing it as Dict - {'tags': { 'data': 'test'}} - Daniel suggests using over riding the JSONfield as:

class JSONField(serializers.Field):
 def to_representation(self, obj):
  return json.loads(obj)
......

However the data is still stored as dict. In my serializers.py I've the overridden the JSONField class and then used it as such

class schemaserializer(serializers.ModelSerializer):
   js_data=serializers.JSONField()

However it still saves it as as a dict. Expected behavior: Save it as JSON - POST

retrieve it as dict - GET (so that the render can parse it as JSON)

Am currently doing this manually using json dumps and json loads, but looking for a better way.

The reason to do this is because although I have an API there are instances where users read my DB directly and they need the field to be in a JSON.

Django (2.0.1) Python 3.5 djangorestframework (3.7.7)

Shaikh Saleem
  • 75
  • 1
  • 6

2 Answers2

0

Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into JSON, XML or other content types.

See more at serializers docs

What you need is:

class SchemaSerializer(serializers.ModelSerializer):
    class Meta:
        model = YOUR_MODEL_NAME
        fields = A_LIST_OF_FIELD

and then in your view:

class SchemaView(mixins.ListModelMixin, generic.GenericAPIView):
    queryset = YOUR_MODEL_NAME.objects.all()
    serializer_class = SchemaSerializer
webbyfox
  • 1,049
  • 10
  • 22
  • Hi, Thank you for you reply. But am already doing this. DRF stores the JSON as Dict and when responding to an API it parses the Dict into a JSON, as expected. However I've also got users who read directly from the DB they need data to be stored as JSON. Therefore I need a way that stores the Data as JSON and when responding to an API parse the data as dict and sent it to Response() obj to be converted as JSON. Am currently doing this manually using json dumps and loads, looking for a better way. – Shaikh Saleem Feb 23 '18 at 05:43
0

Do you mean you want to use the actual JSON type in your database backend? If so, you would want to use the appropriate JSONfield type on your model instead of in the serializer specifically.

MrName
  • 2,363
  • 17
  • 31
  • Thank you for you reply. You are right, I do want to store data as actual JSON, however I cannot change the field type to JSON, its not under my control. I have to figure out a way to do this using serializer. As I mentioned I am able to do it manually but that's not clean code, looking for a better way. – Shaikh Saleem Feb 23 '18 at 05:42