1.代码model设计
class RoleInfo(models.Model): choices=[(‘0‘,‘普通角色‘),(‘1‘,"管理员")] status_enum= [(‘0‘,‘禁用‘),(‘1‘,"启用")] role_name = models.CharField(max_length=50) role_type = models.CharField(choices=choices,max_length=10) status = models.CharField(choices=status_enum,max_length=10) create_time = models.DateTimeField(auto_now_add=True) update_time = models.DateTimeField(auto_now=True) class Meta: db_table = "tbl_role_info" ordering = ["-create_time"]
2.serializer 设计:
class RoleSerializer(serializers.ModelSerializer): role_type_value = serializers.SerializerMethodField() status_value = serializers.SerializerMethodField() def get_role_type_value(self,obj): return obj.get_role_type_display() def get_status_value(self,obj): return obj.get_status_display() class Meta: model = models.RoleInfo fields= [‘id‘,‘role_name‘,‘role_type‘,‘role_type_value‘, ‘status‘,‘status_value‘,‘create_time‘,‘update_time‘]
返回数据:
{
"next": null,
"previous": null,
"data": [
{
"id": 1,
"role_name": "testrole",
"role_type": "0",
"role_type_value": "普通角色",
"status": "0",
"status_value": "禁用",
"create_time": "2021-08-02 19:24:27",
"update_time": "2021-08-02 19:24:27"
}
],
"page_size": 10,
"page": 1,
"totals": 1,
"msg": "ok",
"code": 200,
"success": true
}
方式二:
class RoleSerializer(serializers.ModelSerializer): role_type_value = serializers.CharField(source="get_role_type_display",max_length=10,read_only=True) status_value = serializers.CharField(source="get_status_display",max_length=10,read_only=True) class Meta: model = models.RoleInfo fields= [‘id‘,‘role_name‘,‘role_type‘,‘role_type_value‘, ‘status‘,‘status_value‘,‘create_time‘,‘update_time‘]
返回也可以达到一样的预期结果