Django Rest Framework:在JSON对象中循环 [英] Django Rest Framework: Loop inside JSON OBJECT

查看:60
本文介绍了Django Rest Framework:在JSON对象中循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好我是Django和Python的新手...我正在使用REST Framework开发一些Web服务。我想遍历JSON项目的所有订单。来自javascript的请求是通过以下方式完成的:

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


}

在Django方面,我有。

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) 

如果在javascript中我将我的对象字符串化在发送之前,上面的代码可以正常工作。问题是当我不进行字符串化时。

If In javascript i stringify my object before to send it the above code works fine. The problems is when I don't stringify.

如果我进行字符串化

request.body = 
b'{"Orders":[{"id":1,"Name":"Name1","Description":"Description1"},{"id":2,"Name":"Name2","Description":"Description2"},{"id":3,"Name":"Name3","Description":"Description3"}]}'

如果我不进行字符串化

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'

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']}>

我可以毫不犹豫地说。但是我想了解是否有可能在没有从我拥有的QueryDict开始的情况下获得同样的结果。

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.

谢谢

推荐答案

您不仅以不必要的冗长和复杂的方式构造了JSON对象,而且还使用了错误的数据结构。如果要迭代,则应该是一个数组(映射到Python中的列表),而不是对象(映射到dict)。您的JS代码应如下所示:

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.)

现在,在Python中进行迭代很简单:

Now, it's simple to iterate in Python:

for obj in jsondata['Orders']:
    ...

这篇关于Django Rest Framework:在JSON对象中循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆