Harry
Harry

Reputation: 13329

Saving valid JSON into JSONField via Django Rest Framework

I'm using Django version 1.10.5 and Django Rest Framework 3.5.3 I als installed pip install jsonfield. My model has this field:

tags = JSONField(blank=True, default="")

This is the data I send to my server:

{
    "latitude": 31.65431,
    "longitude": -28.29471,
    "accuracy": 5,
    "upload_type":"3",
    "share_group":1555,
    "description": "Testing a event from mobile application",
    "timestamp": "2017-02-16T09:27:23Z",
    "tags": [{"tagId": 29,"values": [{"fieldId": 193,"value": "CYX 544 GP"},{"fieldId": 194,"value": ""}]}]
}

I get this error:

"tags": ["Not a valid string."]

The only way to get this to save is this:

"tags":[{'tagId': 29,'values': [{'fieldId': 193,'value': 'CYX 544 GP'},{'fieldId': 194,'value': ''}]}]"

Sure, I can just do a replace("'",'"") to get this to be valid json, but this seems like a hack.

How am I supposed to send JSON and save it as JSON using the rest framework?

Upvotes: 4

Views: 4203

Answers (1)

Harry
Harry

Reputation: 13329

Ok, this worked:

class EventSerializer(serializers.ModelSerializer):
    tags = serializers.JSONField()
    class Meta:
        model = Event
        fields = ('client', 'latitude', 'upload_type', 'accuracy', 'longitude', 'description', 'tags', 'timestamp')

Upvotes: 4

Related Questions