You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Django REST Framework序列化器中通过query_set展示模型选项值?

解决序列化时显示Category对象而非选项值的问题

问题原因

你当前使用PrimaryKeyRelatedField序列化category字段,同时指定source="category.category",但该字段原本是用来处理外键关联的主键值,并不适配Choice类型字段的序列化需求,因此导致界面输出异常的Category object('number')内容。

解决方案

根据你需要显示的内容类型,提供两种可行方案:

方案1:显示Choice的键值(如VIDEOGAMES、ANIME)

直接用CharField指定对应source,同时设置read_only=True避免反序列化问题:

class ImageCategorySerializer(serializers.ModelSerializer):
    category = serializers.CharField(source="category.category", read_only=True)
    image = serializers.IntegerField(source="image.id")
    
    class Meta:
        fields = '__all__'
        model = ImageCategory

方案2:显示Choice的友好名称(如Videogames、Anime)

使用SerializerMethodField自定义序列化逻辑,调用Django模型自带的get_<field_name>_display()方法获取Choice的友好名称:

class ImageCategorySerializer(serializers.ModelSerializer):
    category = serializers.SerializerMethodField()
    image = serializers.IntegerField(source="image.id")
    
    def get_category(self, obj):
        # 获取category字段对应的友好显示名称
        return obj.category.get_category_display()
    
    class Meta:
        fields = '__all__'
        model = ImageCategory

额外优化(可选)

如果希望Category模型在任何场景下的字符串表示都是友好名称,可以在Category模型中重写__str__方法:

class Category(models.Model):
    # ... 原有代码 ...
    
    def __str__(self):
        return self.get_category_display()

内容的提问来源于stack exchange,提问作者Br0k3nS0u1

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 07:16:30