ModelSerializers & schema generation

56 views
Skip to first unread message

Adam Fletcher

unread,
Aug 21, 2021, 2:44:12 PM8/21/21
to django-res...@googlegroups.com
Hi DRFers,

I have a model like this:

class Job(Model):

    class JobState(IntEnum):
        RECEIVED = 0
        PROCESSING = 1
        DONE = 2
        FAILED = 3

        @classmethod
        def choices(cls: Any) -> List[Tuple[int, str]]:
            return [(key.value, key.name) for key in cls]

    state = IntegerField(
        choices=JobState.choices(),
        default=JobState.RECEIVED,
    )


I have a ModelSerializer:
class JobSerializer(serializers.ModelSerializer):
    class Meta:
        model = Job
        fields = [
            "state",
        ]

How do I get the OpenAPI schema to show the _names_ of the fields, not the enum values?

My schema generates to:

"state": {
"enum": [
0,
1,
2,
3
],
"type": "integer",
"minimum": -2147483648,
"maximum": 2147483647
},

Any ideas on how to make the enum use the name, not the value?

Thanks!
-Adam

Carl Nobile

unread,
Aug 21, 2021, 3:40:49 PM8/21/21
to django-res...@googlegroups.com
In this part do this:

class JobState(IntEnum):
    RECEIVED = 0
    PROCESSING = 1
    DONE = 2
    FAILED = 3
    INT_ENUM = {'RECEIVE': RECEIVE, 'PROCESSING': PROCESSING,
                'DONE': DONE, 'FAILED': FAILED}

Then use the INT_ENUM in your serializer. This may not work exactly in your case, however, it could be useful.
I do this all the time, but I don't make another embedded class, I don't see any real need for it. Just use the standard Django way to create an iterator for a model field. https://docs.djangoproject.com/en/3.2/ref/models/fields/#django.db.models.Field.choices

~Carl

--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-fram...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-rest-framework/CAEP43uOWYYhQ8hH7xt0qqOk9E4D9rW0Z0OzDyYqKvnE0pg2jSQ%40mail.gmail.com.


--
-------------------------------------------------------------------------------
Carl J. Nobile (Software Engineer)
carl....@gmail.com
-------------------------------------------------------------------------------

Adam Fletcher

unread,
Aug 22, 2021, 7:39:23 PM8/22/21
to django-res...@googlegroups.com
Thanks!

I ended up adding a @classmethod to my enum to get the names back, then in my serializer:
    state = serializers.ChoiceField(choices=Job.JobState.names())

Which worked great.


Reply all
Reply to author
Forward
0 new messages