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'
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"
}
]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With