'drf-yasg, How to add model choices on api doc?
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:
I wanna show the 'boss'/'leader'/'bro'/'sis' in the red rectangle.
I googled, but not found solutions, so here is the questions.
Solution 1:[1]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Egor Wexler |

