django-rest-frameworkdrf-yasg

How can I display ordering using drf_yasg


How to deal with ordering in drf_yasg?

I have a View:

class ContentView(ModelViewSet):
    ....
    ordering_fields = ['price',]

But when I open swagger I cant see this possibility.


Solution

  • I found a solution, maybe somebody need this too.

    I use django_filters package and in this case we should use filter_class on our view and there we can define ordering as we need.

    Example:

    from django_filters import rest_framework as filters, OrderingFilter
    
    from contents.models import Content
    
    
    class ContentFilter(filters.FilterSet):
    
        order = OrderingFilter(
            # tuple-mapping retains order
            fields=(
                ('price', 'price'),
            ),
    
            field_labels={
                'price': 'Content price',
            }
        )
    
        class Meta:
            model = Content
            fields = ['price']
    
    
    # my view in views.py
    
    class ContentView(ModelViewSet):
            filter_class = ContentFilter
            .....
    

    Now you can use ordering ?order=price or ?order=-price and you can see it on swagger docs enter image description here

    More info about OrderingFilter in django_filters here