django-枚举类型扩展方法
原文地址: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']
posted on 2018-10-13 12:11 new_candy 阅读(2099) 评论(0) 编辑 收藏 举报