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

在Django Rest Framework中获取数组类型选择字段的标签

解决DRF中ArrayField类型选择字段的标签数组返回问题

针对你遇到的ArrayField存储多选值无法直接用get_field_display获取标签的问题,可以通过在序列化器中添加SerializerMethodField手动映射标签,实现返回类似"other": ["Cigar"]的格式。

具体修改步骤:

  1. 修改TobaccoUseSerializer,新增自定义字段处理tu_other_use的标签转换:
    • 将模型中的OTHER_USE_CHOICES转为字典,快速通过存储值匹配对应标签
    • 遍历tu_other_use数组,逐个替换为标签,同时处理空值场景

修改后的完整序列化器代码:

class TobaccoUseSerializer(serializers.ModelSerializer):
    status = serializers.CharField(source='get_tu_smoking_status_display')
    other = serializers.SerializerMethodField()  # 新增自定义标签字段

    class Meta:
        model = TobaccoUse
        # 保留原字段并新增other,若要隐藏原tu_other_use,可改为exclude=('tu_other_use',)
        fields = ('__all__', 'other')

    def get_other(self, obj):
        # 把选择项转为键值对字典,存储值为键,显示标签为值
        other_choice_map = dict(TobaccoUse.OTHER_USE_CHOICES)
        # 遍历数组替换标签,空数组返回空列表
        return [other_choice_map.get(item, item) for item in obj.tu_other_use] if obj.tu_other_use else []
  1. 效果验证:
    当tu_other_use存储值为['C', 'CH']时,返回的other字段会是["Cigar", "Chew"],完全匹配需求格式。

补充优化:

如果想避免每次序列化都重复生成字典,可将映射字典定义在序列化器外部:

# 序列化器外部定义,全局复用
OTHER_USE_CHOICE_MAP = dict(TobaccoUse.OTHER_USE_CHOICES)

class TobaccoUseSerializer(serializers.ModelSerializer):
    status = serializers.CharField(source='get_tu_smoking_status_display')
    other = serializers.SerializerMethodField()

    class Meta:
        model = TobaccoUse
        fields = ('__all__', 'other')

    def get_other(self, obj):
        return [OTHER_USE_CHOICE_MAP.get(item, item) for item in obj.tu_other_use] if obj.tu_other_use else []

内容的提问来源于stack exchange,提问作者Eric J.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 03:26:07