Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 920
garetHollamdaf Avatar asked Jan 20 '18 16:01

garetHollamdaf


People also ask

What is jsonfield in serializers in Django REST framework?

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.

What does JSON mean?

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.

What is the use of @jsonfield?

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 –

What is serializing in Django?

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.


Video Answer


1 Answers

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'}
like image 197
garetHollamdaf Avatar answered Oct 18 '22 03:10

garetHollamdaf