我怎样才能收到 Django 中的字典列表?

How can I receive a list of dictionaries in djano?

你好,我正在做一个 djago 项目,我想收到一个字典列表,就像这样: [{1: 20}, {2:30}, {3: 50}, ......] 这里 keyid of the productvalueprice 而下面的代码只是收到这样的 single dictionary {"id": 1, "price" : 20} 我想把它改成我上面提到的样子

 list_of_objects = []
        try:
            id = int(request.payload.get("id"))
            price = int(request.payload.get("price"))
            list_of_objects.append({
                "id" : id,
                "price" : price
            })
        except ValueError:
            return response.bad_request("Invalid price, %s, should be in whole dollars" % price)



我不知道该怎么做 谢谢

试试这个

        list_of_objects = []
        try:
            id = int(request.payload.get("id"))
            price = int(request.payload.get("price"))
            list_of_objects.append({
                id: price   # here changes
            })
        except ValueError:
            return response.bad_request("Invalid price, %s, should be in whole dollars" % price)

这应该可以解决问题:

    your_dict = {}
    try:
        id = int(request.payload.get("id"))
        price = int(request.payload.get("price"))
        your_dict[id] = price
    except ValueError:
        return response.bad_request("Invalid price, %s, should be in whole dollars" % price)

这对我有用;我刚才也做了同样的事情。

request_dict = dict(request.payload)

希望对你也有用。