如何在django中更改序列化程序中的字段名称

时间:2017-04-06 06:55:07

标签: serialization django-rest-framework

我有一个字段country_id和country_name,我想在Django rest Framework中更改这两个字段的名称

现在写我正在获取此数据

{
  "data": [
    {
      "country_id": 1,
      "country_name": "Afghanistan"
    },
    {
      "country_id": 2,
      "country_name": "Aland Islands"
    } 
  ]
}

我在serializers.py文件中有更改,但对我不起作用

serializers.py

class CountrySerializer(serializers.ModelSerializer):
    name = serializers.SerializerMethodField('country_name')
    class Meta:
        model = Country
        fields = ('country_id', 'name')

在模型中

class Country(models.Model):
    country_id = models.AutoField(primary_key = True)
    country_name = models.CharField(max_length = 128)

    class Meta:
        db_table = 'countries'

我想要这个数据

 {
      "data": [
        {
          "id": 1,
          "name": "Afghanistan"
        },
        {
          "id": 2,
          "name": "Aland Islands"
        }
      ]
    }

获取此错误:/ false / location / countries /处的AttributeError 'CountrySerializer'对象没有属性'country_name'

1 个答案:

答案 0 :(得分:8)

您必须更改" serializers.py"文件

class CountrySerializer(serializers.ModelSerializer):
    name = serializers.CharField(source='country_name')
    id = serializers.CharField(source='country_id')
    class Meta:
        model = Country
        fields = ('id', 'name')

然后你会得到这样的数据

 {
      "data": [
        {
          "id": 1,
          "name": "Afghanistan"
        },
        {
          "id": 2,
          "name": "Aland Islands"
        }
      ]
    }