Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change field name in serializers in django

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'

like image 905
Harman Avatar asked Apr 06 '17 06:04

Harman


1 Answers

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"
        }
      ]
    }
like image 165
Jaskaran singh Rajal Avatar answered Oct 04 '22 11:10

Jaskaran singh Rajal