0

I have a model like this:

class User(AbstractUser):
    PERMISSION_CHOICES = [
        (0, 'boss'),
        (1, 'leader'),
        (2, 'bro'),
        (3, 'sis'),
    ]

    permission = models.SmallIntegerField(
        _('permission'),
        default=0,
        choices=PERMISSION_CHOICES,
        help_text=_('xxx')
    )

My Serializer is like this:

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('permission', ...)

Now I have the doc like below:

enter image description here

I wanna show the 'boss'/'leader'/'bro'/'sis' in the red rectangle.

I googled, but not found solutions, so here is the questions.

  • If you're using DRF (3.6.3) then you can do like this `permission = serializers.CharField(source='get_permission_display')` – Ankit Tiwari May 07 '22 at 10:28
  • Does this answer your question? [Django Rest Framework with ChoiceField](https://stackoverflow.com/questions/28945327/django-rest-framework-with-choicefield) – Ankit Tiwari May 07 '22 at 10:29
  • 1
    @AnkitTiwari Thanks, bro. This worked in the code which I really send to front-end. But what I wanna is show the enum value & display in the api docs. Show the display in the docs can help front-end coder understand what's the enum value mean. – 我要改名叫嘟嘟 May 09 '22 at 02:22

1 Answers1

0

Nothing is wrong in this representation of the model by Swagger - what you see is what you get.

If you call this API - in your payload field permission will be integer. E.g.:

{
    "permission": 0
}

So if you want this to be changed in Swagger - it will be changed on the model (serializer) as well and therefore your API result will be also amended. I.e.:

{
    "permission": "boss"
}

If it's what you're looking for - then you need to define a custom property on the serializer as so:

class UserSerializer(serializers.ModelSerializer):
    permission = serializers.SerializerMethodField()

    def get_permission(self, obj):
        return obj.get_permission_display()

    class Meta:
        model = User
        fields = ('permission', ...)

More different options to achieve it can be found here: Django Rest Framework with ChoiceField

Egor Wexler
  • 1,754
  • 6
  • 22