I am learning Django Rest Framework and creating some APIs with success. Now I am trying to serialize a relation, but I don't know how this works. Here is my code:
class Countries(models.Model):
country = models.CharField(max_length=255)
class Meta:
managed = False
db_table = 'countries'
class Users(models.Model):
name = models.CharField(max_length=255)
email = models.CharField(max_length=255)
country = models.ForeignKey(Countries, models.DO_NOTHING)
date = models.DateTimeField()
class Meta:
managed = False
db_table = 'users'
In views.py
def get(self,request):
print(UsersSerializer)
users = Users.objects.all()
serializer = UsersSerializer(users,many = True)
return Response(serializer.data)
Serializer:
class UsersSerializer(serializers.ModelSerializer):
class Meta:
model = Users
fields = '__all__'
When I run the API I am getting
[
{
"id": 3,
"name": "dsadasd",
"email": "[email protected]",
"date": "2020-05-12T12:15:24Z",
"country": 1
}
]
In the country field I am getting country id and I was expecting the country name here...
sourceattribute onUsersSerializerlike described django-rest-framework.org/api-guide/fields/#source so defining attribute likecountry = serializers.CharField(source='country.name')should work