django choices 字段处理返回枚举值

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
}

 

上一篇:(五) PYSYFT + OPACUS:具有差异隐私的联邦学习


下一篇:python测试开发django-119.model_to_dict会漏掉DateTimeField字段