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 ?
install json library pip install json
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
and save
plus if you want to use sql with your this project i highly recomment you use
instead of
because models.JSONField doesn't go well with SQL