11

I have a field country_id and country_name and i want to change the name for both fields in Django rest Framework

write now I'm getting this data

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

I have change in serializers.py file but didn't work for me

serializers.py

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

In model

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

    class Meta:
        db_table = 'countries'

I want this data

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

Geting this error: AttributeError at /v1/location/countries/ 'CountrySerializer' object has no attribute 'country_name'

Harman
  • 1,703
  • 5
  • 22
  • 40

1 Answers1

18

You have to change in your "serializers.py" file

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

then you will get data like this

 {
      "data": [
        {
          "id": 1,
          "name": "Afghanistan"
        },
        {
          "id": 2,
          "name": "Aland Islands"
        }
      ]
    }
Jaskaran singh Rajal
  • 2,270
  • 2
  • 17
  • 29
  • Does the actual model field need to be present in the fields Meta attribute, or the fields that are declared in the serializer? Where is the documentation for that? – user3245268 Apr 30 '19 at 14:10
  • For write-able serializers, does the validated_data contain name and id, or country_name and country_id? – user3245268 Apr 30 '19 at 14:11