如何在Django Restframework中使用外键显示名称而不是ID

huangapple go评论75阅读模式
英文:

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

问题

我有一个Django应用程序。还有一个外键关系。但API调用显示的是ID而不是名称。但我想显示名称而不是ID。

所以这是属性:

category = models.ForeignKey(Category, related_name='animals', on_delete=models.CASCADE, verbose_name="test")    

和序列化器:

class SubAnimalSerializer(serializers.ModelSerializer):
    class Meta:
        model = Animal
        fields = ['id', 'name', 'description', 'category', 'pet_list', 'images']
        read_only_fields = ['id']

所以这是API调用的一部分:

"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"
        }
    ],

我当然也搜索了一些东西。所以我找到了这个:

https://stackoverflow.com/questions/70219330/how-to-show-name-instad-of-id-in-django-foreignkey

但它不完全符合我的需求。

问题:如何在API调用中显示名称而不是ID。

英文:

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:

https://stackoverflow.com/questions/70219330/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

答案1

得分: 1

你可以使用 SlugRelatedField 来处理:

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']

为了写入,Category 中的 name 字段应该是唯一的,并最好具有 db_index=True

英文:

You can work with a SlugRelatedField&nbsp;<sup>[drf-doc]</sup>:

<pre><code>class SubAnimalSerializer(serializers.ModelSerializer):
category = <b>serializers.SlugRelatedField(</b>
slug_field='name', queryset=Category.objects.all()
<b>)</b>

class Meta:
    model = Animal
    fields = [&#39;id&#39;, &#39;name&#39;, &#39;description&#39;, &#39;category&#39;, &#39;pet_list&#39;, &#39;images&#39;]
    read_only_fields = [&#39;id&#39;]&lt;/code&gt;&lt;/pre&gt;

In order to write, the name field in Category should be unique, and preferrably have a db_index=True.

答案2

得分: 0

定义一个序列化器中的字段,并像这样使用其 source 属性:

class SubAnimalSerializer(serializers.ModelSerializer):
    category_name = serializers.CharField(source='category.name', read_only=True)  # <====

    class Meta:
        model = Animal
        fields = ['id', 'name', 'description', 'category_name', 'pet_list', 'images']
        read_only_fields = ['id']
英文:

define a field in your serializer and use its source attribute like this:

class SubAnimalSerializer(serializers.ModelSerializer):
    category_name = serializers.CharField(source=&#39;category.name&#39;, read_only=True) # &lt;==== 

    class Meta:
        model = Animal
        fields = [&#39;id&#39;, &#39;name&#39;, &#39;description&#39;,&quot;category_name&quot;,&quot;pet_list&quot;, &#39;images&#39; ]
        read_only_fields = [&#39;id&#39;]

huangapple
  • 本文由 发表于 2023年7月27日 20:26:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76779737.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定