在django-rest-swagger中将枚举呈现为下拉列表

时间:2018-11-14 09:48:56

标签: django django-rest-framework django-rest-swagger

我正在尝试获取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)
                )
            )
        ]

但这并没有显示为下拉列表。

我们如何将选择呈现为下拉菜单?

1 个答案:

答案 0 :(得分:0)

尝试:

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