[英]Update data in a JsonField django
我想更新django中jsonfield中的json對象,我在更新數據時遇到問題。
我的模型看起來像這樣https://codeshare.io/Gbeonj
我的json看起來像這樣https://codeshare.io/5obDPX
所以基本上json具有錯誤的數據,而不是“ NATIONAL ID Card”,它具有“ NATIONAL ID”,因此我想更新此json對象以具有正確的數據。 這是在說什么
"info": {
"mobilePhone": "",
"firstName": "david",
"tags": [],
"middleName": "mirale",
"gender": "Male",
"documentType": "NATIONAL ID",
"beneficiary": false,
"dateOfBirth": "1995-03-04T08:01:42.165Z",
"documentNumber": "519011016721",
"dateOfBirthExact": false,
"role": "Child",
"lastName": "ABSURG0058",
"recipient": "Alternate",
"homePhone": ""
},
"documentType": "NATIONAL ID",
應為“ NATIONAL ID卡”
我正在使用以下腳本來更新服務器中的json對象。
import django
django.setup()
import sys
reload(sys) # to re-enable sys.setdefaultencoding()
sys.setdefaultencoding('utf-8')
import json
from django.db import transaction
from maidea.apps.mobile.models import MobileDocument
office = 'sa_de'
#we fetch all the mobile documents from that have failed
uploads = MobileDocument.objects.filter(
status=MobileDocument.ERROR,
mobile_upload__office__slug=office
)
print('Number of uploads fetched: %d' %(uploads.count()))
with transaction.atomic():
for upload in uploads:
for member in upload.data['members']:
try:
doc_type_value = member['info'].get('documentType')
except:
doc_type_value = None
if doc_type_value == 'NATIONAL ID':
doc_type_value = doc_type_value.replace('NATIONAL ID', 'NATIONAL ID Card')
assert doc_type_value == 'NATIONAL ID Card'
upload.save()
問題是該對象沒有被更新,我在做什么錯?
驗證doc_type_value
后,您無需將其重新設置為上upload
對象,則需要更新上upload
對象:
for upload in uploads:
data = upload.data
updated_members = []
for member in data['members']:
try:
doc_type_value = member['info'].get('documentType')
except KeyError:
pass
else:
if doc_type_value == 'NATIONAL ID':
doc_type_value = 'NATIONAL ID Card'
member['info']['documentType'] = doc_type_value
updated_members.append(member)
data['members'] = updated_members
upload.data = data
upload.save()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.