如何在 Django 休息框架中为枚举字段创建序列化程序

how to create serializer for an enum field in django rest framework

我正在 python django rest 框架中编写一个 API,我一直在为 ENUM 创建序列化程序字段,我如何为 ENUM 字段创建序列化程序字段。 我的模型代码是:

class Queue(models.Model):
    class Meta:
        db_table = 'queues'

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True)
    name = models.CharField(max_length=45)
    type = EnumChoiceField(QueueTypes, default=QueueTypes.pending)
    date = models.DateTimeField(auto_now=True)

我正在为此模型编写序列化程序。

class QueueSerializer(serializers.ModelSerializer):
    class Meta:
        model = Queue
        fields = ('__all__')

    id = serializers.CharField(read_only=True)
    name = serializers.CharField(max_length=45, required=True)
    type=?????# what am i supposed to do here?
    date = serializers.DateTimeField(read_only=True)

在 google 上进行了大量搜索后,我终于找到了 EnumchoiceField 序列化问题的答案,以下更改完成了工作。

我的Model.py:

from enumchoicefield import ChoiceEnum, EnumChoiceField

class QueueTypes(ChoiceEnum):
    appointment = "appointment"
    wait = "wait"
    process = "process"
    pending = "pending"

class Queue(models.Model):
    class Meta:
       db_table = 'queues'

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True)
    name = models.CharField(max_length=45)
    type = EnumChoiceField(enum_class=QueueTypes , default=QueueTypes.process)
    date = models.DateTimeField(auto_now=True)
    fk_department = models.ForeignKey(Department, related_name='department',null=True, on_delete=models.CASCADE)

我的Serialize.py:

from enumchoicefield import ChoiceEnum, EnumChoiceField

class QueueSerializer(serializers.ModelSerializer):
    class Meta:
        model = Queue
        fields = ('__all__')

    id = serializers.UUIDField(read_only=True)
    name = serializers.CharField(max_length=45, required=True)
    type = EnumChoiceField(enum_class=QueueTypes)
    date = serializers.DateTimeField(read_only=True)

EnumChoiceField 扩展似乎工作正常,但不能正确支持 HTML 支持呈现 REST Framework,字段序列化为 EnumChoiceField 未呈现。