简体   繁体   English

drf-yasg/drf-spectacular - 过滤器参数的描述

[英]drf-yasg/drf-spectacular - description for filter parameters

EDIT: This question was originally posted when using yasg but I switched to spectacular so both solutions are ok.编辑:这个问题最初是在使用yasg时发布的,但我切换到spectacular所以两种解决方案都可以。

I'm curious if there is a way to tell the yasg or spectacular to add description to django-filter parameters.我很好奇是否有办法告诉yasgspectaculardjango-filter参数添加描述。

I want to tell developers that the parent field is a Country model pk .我想告诉开发人员, parent字段是Country model pk

Model Model

class County(AddressModel):
    parent = models.ForeignKey('Country', verbose_name='Krajina', related_name='counties', on_delete=models.PROTECT, help_text='Krajina')

    class Meta:
        verbose_name = 'Kraj'
        verbose_name_plural = 'Kraje'

Filter筛选

class CountyFilter(FilterSet):
    class Meta:
        model = County
        fields = {
            'name': ['icontains'],
            'parent': ['exact']
        }

Serializer串行器

class CountySerializer(serializers.ModelSerializer):
    class Meta:
        model = County
        fields = ['id', 'name']

View看法

class AddressCountyAutocompleteView(ListAPIView):
    serializer_class = CountySerializer
    filter_backends = [DjangoFilterBackend]
    filterset_class = CountyFilter
    queryset = County.objects.all()
    pagination_class = AddressAutocompletePagination

    def list(self, request, *args, **kwargs):
        return super().list(request, *args, **kwargs)

This is the auto-generated swagger:这是自动生成的 swagger:

在此处输入图像描述

Is it possible to do that without writing a custom scheme?是否可以在不编写自定义方案的情况下做到这一点?

This answer is for spectacular.这个答案是壮观的。 The help text has to be attached somewhere.帮助文本必须附在某处。 If you want to have it on the filter you would need to set the filter field explicitly in order to attach a help text:如果你想在过滤器上使用它,你需要明确设置过滤器字段以附加帮助文本:

class ProductFilter(FilterSet):
    number_id = NumberFilter(help_text='some injected help text')

    class Meta:
        model = Product

alternatively you can override the detected parameter with或者,您可以使用覆盖检测到的参数

@extend_schema_view(
    list=extend_schema(parameters=[
        OpenApiParameter(name='name__icontains', description="some help text")
    ])
)
class AddressCountyAutocompleteView(ListAPIView):

first choice would be more robust imho.恕我直言,第一选择会更强大。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM