1

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 ?

Yan Tian
  • 377
  • 3
  • 11
  • Why you have `mdels.JsonField` in form ? And where do you want to update the values ? – Ahtisham Dec 31 '21 at 04:05
  • updated the post to reflect where I want to update the values. this `models.JsonField` attribute in the `form` is for statistics of form submission results. For example, how many users voted for option-A, and who are those users. – Yan Tian Dec 31 '21 at 05:00

1 Answers1

0

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

Abdul Raffay
  • 169
  • 7
  • `json.load(submission_stats)` gives me error: **`AttributeError: 'list' object has no attribute 'read'`** as my `submission_stats` is a `List` not `Dictionary`. Is changing to `Dictionary` the only way to go ? – Yan Tian Dec 31 '21 at 08:14
  • oops. sorry didn't notice that it was list. try json.load(submission_stats[0]). yeah it the most feasible and logical way to go. then you can retrieve value by keys and update them easily – Abdul Raffay Dec 31 '21 at 09:03