1

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

1
  • Have you solved this problem? I'm facing almost the same problem today.... still can't find a answer. Commented Jun 4, 2019 at 23:33

2 Answers 2

2

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:

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'});

(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:

for obj in jsondata['Orders']:
    ...
Sign up to request clarification or add additional context in comments.

2 Comments

I changed the Javascript code and the object still is a QueryDict. I also need to access to JSONObject.Name. I assume request.data will always be a QueryDict. If I pass my object using JSON.stringify(JSONObject) I'm able to easily convert it with jsondata = request.data stream = io.BytesIO(request.body) obj = JSONParser().parse(stream) for order in obj['Orders']: If I don't stringify the JSONObject I have the querydict I posted on my question and I can't manage to access to orders and loop on them.
Daniel, thank you for your answer. I edited my question now should be more clear.
1

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

1 Comment

not really. I have a device not connected to network which will download locally the list of products and upload a json containing a list of orders, which is the one for which I have the model. Order have a model in the database. List of orders not. Thank you for your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.