Render enums as dropdown in django-rest-swagger

1.1k views Asked by At

I am trying to get the right query parameters shown in the swagger documentation produced by django-rest-swagger

from rest_framework.filters import BaseFilterBackend
from rest_framework.compat import coreapi, coreschema
from django.utils.encoding import force_text
from django.utils.translation import ugettext_lazy as _

from enum import Enum

class MyChoices(Enum):
    ONE = 'ONE'
    TWO = 'TWO'

class KeyFilter(BaseFilterBackend):

    key_param = 'key'
    default_key = 'psc'
    key_title = _('Key')
    key_description = _('Specify the aggregation key.')

    def filter_queryset(self, request, queryset, view):
        key = request.query_params.pop(self.key_param, [self.default_key])[0]
        return ConsumptionAggregate(queryset).aggregate(key)

    def get_schema_fields(self, view):
        assert coreapi is not None, 'coreapi must be installed to use `get_schema_fields()`'
        assert coreschema is not None, 'coreschema must be installed to use `get_schema_fields()`'
        return [
            coreapi.Field(
                name=self.key_param,
                required=False,
                location='query',
                schema=coreschema.Enum(
                    MyChoices,
                    title=force_text(self.key_title),
                    description=force_text(self.key_description)
                )
            )
        ]

But that is not being displayed as a dropdown.

How can we have choices being rendered as dropdowns?

1

There are 1 answers

0
Piotr Karnasiewicz On

Try:

schema=coreschema.Enum(
  ('ONE', 'TWO'),
  title=force_text(self.key_title),
  description=force_text(self.key_description)
)