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

后端 未结 2 917
孤街浪徒
孤街浪徒 2021-02-13 23:36

i am writing an API in python django rest framework and i am stuck at creating a serializer field for an ENUM, how can i create a serializer field for an ENUM field. my model co

2条回答
  •  野性不改
    2021-02-13 23:59

    After doing a lot of searches on google i finally found the answer to the serializing issue with the EnumchoiceField the following changes did the job.

    my 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)
    

    my 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)
    

提交回复
热议问题