Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

enter image description here

Is it possible to do that without writing a custom scheme?

like image 991
Milano Avatar asked Oct 25 '25 05:10

Milano


1 Answers

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.

like image 105
Insa Avatar answered Oct 27 '25 17:10

Insa