Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to show name instead of id with foreighkey with django restframework

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading