如何为多选过滤器生成架构?

时间:2019-04-23 19:27:05

标签: django django-rest-framework swagger django-filter drf-yasg

在我们的API中,我们有一个端点来列出位置。我们允许按位置类型进行过滤,并且允许该过滤器使用多个值。例如:

GET /location/?type=hotel&type=airport

对于过滤,我们使用django-filter。但是,drf-yasg似乎无法正确生成此参数的架构。

视图类可以归结为:

from rest_framework.generics import ListAPIView
from .models import Location
from .serializers import LocationListSerializer
from .filters import LocationFilterSet
from django_filters.rest_framework import DjangoFilterBackend

class LocationListView(ListAPIView):
    queryset = Location.objects.all()
    serializer_class = LocationListSerializer
    filter_backends = (
        DjangoFilterBackend,
    )
    filter_class = LocationFilterSet

,过滤器类如下:

from django_filters import rest_framework as filters
from .models import Location

class LocationFilterSet(filters.FilterSet):
    type = filters.MultipleChoiceFilter(choices=Location.TYPE_CHOICES)

    class Meta:
        model = Location
        fields = (
            'type',
        )

此视图按预期工作-通过以下测试:

from django.test import TestCase
from django.urls import reverse
from rest_framework import status
from .models import Location

class TestLocationView(TestCase):
    def test_filter_by_multiple_types(self):
        Location.objects.create(type='airport')
        Location.objects.create(type='hotel')
        Location.objects.create(type='home')
        response = self.client.get('/location/?type=hotel&type=airport')
        self.assertEqual(len(response.data), 2)

我希望为该参数生成的Yaml看起来像这样:

parameters:
- name: type
  in: query
  description: ''
  required: false
  schema:
      type: array
      items:
          type: string
  explode: true

但是,它看起来像这样:

- name: type
  in: query
  description: ''
  required: false
  type: string

这是drf-yasg的限制吗?

由于无法覆盖过滤器后端生成的架构,因此无法使用swagger_auto_schema的{​​{1}}。

这似乎是因为query_serializer仅输出两个字段类型,即数字和字符串。我继续并覆盖了该方法,但是,它随后在django_filters.rest_framework.backends.DjangoFilterBackend.get_coreschema_field中引发错误,不接受数组类型。

0 个答案:

没有答案