Reputation: 818
I have below json as input from the client
[
{'id': 0, 'name': 'Housing', 'value': 3},
{'id': 1, 'name': 'Bank', 'value': 8},
{'id': 2, 'name': 'Entertainment', 'value': 3}
]
It is being assigned to inputV_wc object in my view like below
View:
def savemore(request):
if request.method == "POST":
data=json.loads(request.body.decode())
inputV_wc = data['wc']
else:
response_data = 'You have not saved any data!'
return HttpResponse(response_data, content_type="text/plain")
try:
if not inputV_wc:
test=''
else:
# WC - Insert wc again on each save rather update - time consuming
if js_wex.objects.filter(pid = request.session.get('pid')).exists():
js_wex.objects.filter(pid=request.session.get('pid')).delete()
wc = js_wex(pid=request.session.get('pid'), wcname=inputV_wc[0]['name'],rating=inputV_wc[0]['value'],ordernum=inputV_wc[0]['id'])
wc.save()
wc = js_wex(pid=request.session.get('pid'), wcname=inputV_wc[1]['name'],rating=inputV_wc[1]['value'],ordernum=inputV_wc[1]['id'])
wc.save()
wc = js_wex(pid=request.session.get('pid'), wcname=inputV_wc[2]['name'],rating=inputV_wc[2]['value'],ordernum=inputV_wc[2]['id'])
wc.save()
except Exception as e:
response_data = 'Ouch! Something went wrong!'+str(e)
return HttpResponse(response_data, content_type="text/plain")
Currently if my input json has 5 rows, certainly the above view fails with Index out of range.. and if input json has 2 rows it again fails with missing entry - model cannot be saved.
How can I write my view such that if json has varied number of objects like
input from one user -
[
{'id': 0, 'name': 'Housing', 'value': 14},
{'id': 1, 'name': 'Bank', 'value': 18}
]
input from other user -
[
{'id': 0, 'name': 'Housing', 'value': 3},
{'id': 1, 'name': 'Bank', 'value': 18},
{'id': 2, 'name': 'Housing1', 'value': 14},
{'id': 3, 'name': 'Bank1', 'value': 12}
]
can be handled ?
Json rows could be from 1 to 15 maximum for each input.
I read about using **kwargs, for handling similar scenario.. but I couldn't figure out how to apply for saving my model for varied json input.
Upvotes: 1
Views: 40
Reputation: 11591
If I understand you correctly, I think you just want to use a for
statement:
for row in inputV_wc:
wc = js_wex(pid=request.session.get('pid'), wcname=row['name'], rating=row['value'], ordernum=row['id'])
wc.save()
If you want to insert all the objects at once, based on what you have shown you could probably use bulk_create
:
rows = []
for row in inputV_wc:
wc = js_wex(pid=request.session.get('pid'), wcname=row['name'], rating=row['value'], ordernum=row['id'])
rows.append(wc)
js_wex.objects.bulk_create(rows)
Upvotes: 1