5

在我们的 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's query_serializer,因为它不允许覆盖过滤器后端生成的模式。

这似乎是因为django_filters.rest_framework.backends.DjangoFilterBackend.get_coreschema_field只输出两种字段类型,数字和字符串。我继续并覆盖了该方法,但是,它随后抛出错误drf_yasg.inspectors.query.CoreAPICompatInspector.coreapi_field_to_parameter,不接受数组类型。

4

0 回答 0