Hi Guys I'm new to Django and Python... I'm using REST Framework to develop some webservices. I want to loop through all the orders of a JSON item. The request from javascript is done in this way:
function TestDjangoPostWithNoCsrlTokenAndWithMultipleObjectsJson() {
var JSONObject = new Object();
JSONObject.Orders = [];
JSONObject.Orders.push({ id: 1, Name: 'Name1', Description: 'Description1' });
JSONObject.Orders.push({ id: 2, Name: 'Name2', Description: 'Description1' });
JSONObject.Orders.push({ id: 3, Name: 'Name3', Description: 'Description1' });
console.log(JSON.stringify(JSONObject));
$.ajax
({
type: "POST",
url: URL_PostOrdersMultipleObjects,
headers: {
"Authorization": "Basic " + btoa("xxx" + ":" + "xxx")
},
data: JSONObject,
dataType: 'json',
success: function (data, status, xhr) {
console.log(JSON.stringify(data));
if (xhr.readyState == 4) {
if (xhr.status == 201) {
console.log("Created");
}
} else {
console.log("NoGood");
}
},
complete: function (xhr) {
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr.status);
console.log(thrownError);
}
});
}
On Django side, I have...
@api_view(['GET', 'POST'])
def JSONPostTest(request):
if request.method == 'POST':
stream = io.BytesIO(request.body)
obj = JSONParser().parse(stream)
for order in obj['Orders']: # First Example
serializer = QASerializer(data=order)
if serializer.is_valid():
serializer.save()
else :
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
return Response('OK', status=status.HTTP_201_CREATED)
else:
return Response('OK', status=status.HTTP_201_CREATED)
If In javascript i stringify my object before to send it the above code works fine. The problems is when I don't stringify.
If I stringify
request.body =
b'{"Orders":[{"id":1,"Name":"Name1","Description":"Description1"},{"id":2,"Name":"Name2","Description":"Description2"},{"id":3,"Name":"Name3","Description":"Description3"}]}'
if I don't stringify
request.body
b'Orders%5B0%5D%5Bid%5D=1&Orders%5B0%5D%5BName%5D=Name1&Orders%5B0%5D%5BDescription%5D=Description1&Orders%5B1%5D%5Bid%5D=2&Orders%5B1%5D%5BName%5D=Name2&Orders%5B1%5D%5BDescription%5D=Description1&Orders%5B2%5D%5Bid%5D=3&Orders%5B2%5D%5BName%5D=Name3&Orders%5B2%5D%5BDescription%5D=Description1'
and
request.data
<QueryDict: {'Orders[1][Description]': ['Description1'], 'Orders[2][id]': ['3'], 'Orders[0][Name]': ['Name1'], 'Orders[0][Description]': ['Description1'], 'Orders[2][Description]': ['Description1'], 'Orders[1][id]': ['2'], 'Orders[0][id]': ['1'], 'Orders[1][Name]': ['Name2'], 'Orders[2][Name]': ['Name3']}>
I can stringify no problem on that. But I want to understand if it's possible to obtain the same result without stringifing starting from the QueryDict I have.
Thank you
You've not only constructed your JSON object in an unnecessarily verbose and complex way, you're also using the wrong data structure. If you want to iterate something, it should be an array (which maps to a list in Python), not an object (which maps to a dict). Your JS code should look like this:
(You could actually make that more compact by defining the objects inline with the array, but this is at least clearer for now.)
Now, it's simple to iterate in Python:
Since you write you have a Serializer for Order I assume it is also a model on your backend and you would like to store it in the database. In that case I would not bother to manually deserialize the list of orders but let django-restframework unpack the nested child objects along with the parent.
Have a look here: https://stackoverflow.com/a/28246994/640916