我有下课的定义来做投票系统的统计。
class FormPage(AbstractForm):
submission_stats = models.JSONField(null=True, editable=False)现在,我有了以下格式的submission_stats:
[
{
"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":[
]
}
]
}
]例如,当我收到两个选票提交时,我希望相应地更新num_vote (从0到2)和user_list (从[]到[user_a, user_b])字段。
如何查询和更新嵌套JSONField数据中的元素?
发布于 2021-12-31 06:45:28
安装json库pip安装json
import json
data = json.load(submission_stats)现在,这些数据是python字典。想更新就更新
若要将更新的数据保存回json字段,请将字典转换为json,如下所示
json.dumps(data, indent = 4)和拯救
另外,如果您想在这个项目中使用sql,我会高度重新注释您使用的
from django_extensions.db.fields.json import JSONField而不是
models.JSONField因为models.JSONField不适合使用SQL
https://stackoverflow.com/questions/70538753
复制相似问题