Reputation: 1105
I am trying to create a serializer which has only one JSONField
class DataSerializer(serializers.Serializer):
data = serializers.JSONField()
When I am trying to use this serializer in the shell as -
>>> s = DataSerializer(data={"name": "Tom"})
>>> s.is_valid()
False
>>> s.errors
{'data': [ErrorDetail(string='This field is required.', code='required')]}
I don't know what I am doing wrong. Please bear with me if its a too simple question as I am new to using DRF.
Upvotes: 1
Views: 2699
Reputation: 3091
This is the way you have to send the data in:
s = DataSerializer(data={"data" : {"name": "Tom"}})
Perhaps, your choice to name your jsonfield `data' confused you little bit here.
The parameter data
when constructing the serializer is just a parameter which it uses to set the data to serialize.
When you call is_valid
, it looks at the data passed in to the serializer and tries to find the JSONField named data
in this case.
If you renamed it to let's say jsondata, it would try to find jsondata in the data. In that case, you would do:
s = DataSerializer(data={"jsondata" : {"name": "Tom"}})
Hope it is clear.
Upvotes: 4