其他分享
首页 > 其他分享> > django choices 字段处理返回枚举值

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
}

 

标签:status,models,value,django,枚举,role,time,choices,type
来源: https://www.cnblogs.com/SunshineKimi/p/15091365.html