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

…衆ロ難τιáo~ 提交于 2020-06-10 10:07:06

问题


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 code is:

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)

and i am writing a serializer for this model.

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)

回答1:


The EnumchoiceField extension seems to work fine but does not correctly support the HTML support render of the REST Framework, fields serialized as EnumChoiceField are not rendered.




回答2:


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)


来源:https://stackoverflow.com/questions/43088804/how-to-create-serializer-for-an-enum-field-in-django-rest-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!