How to query and update nested JSON data in Django

807 Views Asked by At

I have below class defined to do statistics for voting system.

class FormPage(AbstractForm):
    submission_stats = models.JSONField(null=True, editable=False)

Now, I have submission_stats in below format:

[
   {
      "id":4,
      "label":"checkboxes",
      "choices":[
         {
            "content":"option-A",
            "num_vote":0,
            "user_list":[
               
            ]
         },
         {
            "content":"option-B",
            "num_vote":0,
            "user_list":[
               
            ]
         },
         {
            "content":"option-C",
            "num_vote":0,
            "user_list":[
               
            ]
         }
      ]
   },
   {
      "id":7,
      "label":"Radio Button",
      "choices":[
         {
            "content":"option-1",
            "num_vote":0,
            "user_list":[
               
            ]
         },
         {
            "content":"option-2",
            "num_vote":0,
            "user_list":[
               
            ]
         },
         {
            "content":"option-3",
            "num_vote":0,
            "user_list":[
               
            ]
         }
      ]
   }
]

When I receive 2 vote submissions for example, I want to update num_vote (from 0 to 2) and user_list (from [] to [user_a, user_b]) field in this JSONField accordingly.

How to query and update elements in nested JSONField data please ?

1

There are 1 best solutions below

2
Abdul Raffay On

install json library pip install json

import json

data = json.load(submission_stats)

now this data is python dictionary. update it however you want

to save updated data back to json field, convert dictionary back to json like this

json.dumps(data, indent = 4)

and save

plus if you want to use sql with your this project i highly recomment you use

from django_extensions.db.fields.json import  JSONField

instead of

models.JSONField

because models.JSONField doesn't go well with SQL