garetHollamdaf
garetHollamdaf

Reputation: 379

How to append/delete data from JSONField in django

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

Upvotes: 9

Views: 10123

Answers (1)

garetHollamdaf
garetHollamdaf

Reputation: 379

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'}

Upvotes: 8

Related Questions