I have a JSONField
which has some data like this :
{'key_one' : 'val_one',
'key_two' : 'val_two'}
I want to add data to it as well as deleting data from it.
So far i can just give it a value not appending to it.
I'm using mySql
database
This article revolves around JSONField in Serializers in Django REST Framework. JSONField is basically a field class that validates that the incoming data structure consists of valid JSON primitives. In its alternate binary mode, it will represent and validate JSON-encoded binary strings.
JSON is a simple format to store data in key and value format. It is written in curly braces. Many a time, on developer website, we need to add developer data and JSON fields are useful in such cases. First create a Django project and an app.
JSONField is basically a field class that validates that the incoming data structure consists of valid JSON primitives. In its alternate binary mode, it will represent and validate JSON-encoded binary strings. It has the following arguments –
In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Every serializer comes with some fields (entries) which are going to be processed. For example if you have a class with name Employee and its fields as Employee_id, Employee_name, is_admin, etc.
For appending to JSONField
or any other JSON in python
:
my_json = {'key_one' : 'val_one',
'key_two' : 'val_two'}
same as :
my_json = Model.objects.get(pk=id).my_json_field
Append to json
:
my_json['new_key'] = 'new_val'
print (my_json)
{'key_one' : 'val_one',
'key_two' : 'val_two',
'new_key' : 'new_val'}
Delete from json
:
my_json.pop('new_key')
print (my_json)
{'key_one' : 'val_one',
'key_two' : 'val_two'}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With