简体   繁体   中英

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.

I'm curious if there is a way to tell the yasg or spectacular to add description to django-filter parameters.

I want to tell developers that the parent field is a Country model pk .

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:

在此处输入图像描述

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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