I have a django application. And a foreign relationship. But the api calls shows the id instead of the name. But I want to show the name instead of the id.
So this is the property:
category = models.ForeignKey(Category, related_name='animals', on_delete=models.CASCADE, verbose_name="test")
and serializer:
class SubAnimalSerializer(serializers.ModelSerializer):
class Meta:
model = Animal
fields = ['id', 'name', 'description',"category","pet_list", 'images' ]
read_only_fields = ['id']
so this is part of the api call:
"animals": [
{
"id": 3,
"name": "Vicuña",
"description": "kjhkkhkhkjhjkhj Hello",
"category": 6,
"pet_list": "D",
"images": "http://192.168.1.135:8000/media/media/photos/animals/mammal.jpg"
},
{
"id": 5,
"name": "Goudhamster",
"description": "khkjh",
"category": 6,
"pet_list": "C",
"images": "http://192.168.1.135:8000/media/media/photos/animals/imgbin_dog-grooming-puppy-cat-pet-png_I7rLPen.png"
}
],
And I googled something ofcourse. So I found this:
How to show name instad of id in django ForeignKey?
But it doesn’t exactly fit what I am looking for.
Question: how to show name instead of id in api call
>Solution :
You can work with a SlugRelatedField [drf-doc]:
class SubAnimalSerializer(serializers.ModelSerializer):
category = serializers.SlugRelatedField(
slug_field='name', queryset=Category.objects.all()
)
class Meta:
model = Animal
fields = ['id', 'name', 'description', 'category', 'pet_list', 'images']
read_only_fields = ['id']
In order to write, the name field in Category should be unique, and preferrably have a db_index=True.