将 JSON 字段分配给 django 中的模型变量

Assign JSON field to model variable in django

我 json 喜欢:

{
   "name": "Rahul",
   "2or4": 2,

}

这里,

如何将我的模型变量:twoOrFour 分配给 jason 字段值“2or4” 因为我们不能让变量以整数开头。

我是 django 的新手。我为此使用 dJango-rest-framework api.

您可以尝试将 twoOrFour 添加到您的 JSON 对象。例如:

import json

data = {'name': 'Rahul', '2or4': 2}

data = json.loads(data) # convert to Python dict
data['twoOrFour'] = data['2or4'] # append twoOrFour
data = json.dumps(data) # convert back to JSON object

现在 JSON 对象有 twoOrFour 字段。希望有用。

如果您使用的是 djangorestframework,则需要在序列化程序中重写 to_representation 函数

http://www.django-rest-framework.org/api-guide/serializers/#overriding-serialization-and-deserialization-behavior

应该是这样的

def to_representation(self, obj)
    serialized_data = super(SerializerClassName, self).to_representation(obj)
    serialized_data["2or4"] = serialized_data["twoOrFour"]
    //Remove the old field name
    del serialized_data["twoOrFour"]
    return serialized_data

此代码应该在 SerializerClassName 是您的序列化器 class 名称的情况下工作