I have a model like this:
class Things(models.Model):
data = models.JSONField(default=dict)
and structure of data
is like this:
{
"item" : "sugar",
"quantity" : "2",
"cost" : 220
}
Note that it is not mandatory for data
to contain all 3 keys, all of them are optional.
The difficult part is that I don't want any other keys, apart from these 3 keys, to be present in data
field.
Creating a serializer can help to ensure presence and format of these 3 fields but it will not ensure absence of other fields. How can I achieve this thing in django rest framework?
You can validate the field in your serializer:
You can also create a separate serializer for your data field and pass the value to it, validate each field there and return the final data. But this should do if your fields are limited and simple.