原文地址:https://docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.Model.get_FOO_display
關於django中枚舉類型轉換顯示問題,每次設置枚舉類型,
EXPERIENCE_CHOICES = ( (1, '應屆畢業生'), (2, '3年及以下'), ... )
education = models.SmallIntegerField(choices=EDUCATION_CHOICES, default='不要求', verbose_name="學歷要求")
數據庫實際存儲值為,1,2,3, 4, 5,序列化返回數據類型:
[ { "id": 2, "name": "Python開發工程師", "salary": 3, "experience": 2, "education": 2, "type": 1, "create_time": "2018-12-11T10:48:03.076841+08:00", } } },
...
]
如果想要在序列化返回時顯示對應的字符串信息,只需要在序列化器中聲明字段時指定source來源
class LatestJobSerializer(serializers.ModelSerializer): salary = serializers.CharField(source='get_salary_display') experience = serializers.CharField(source='get_experience_display') education = serializers.CharField(source='get_education_display') type = serializers.CharField(source='get_type_display') class Meta: model = Job fields = ['id', 'name', 'salary', 'experience', 'education', 'type', 'create_time', 'enterprise', 'locations', 'url']
