Skip to content

Incorrect handling of sort field in schema generation #1120

@atkallie

Description

@atkallie

Description of the Bug Report

I believe that the handling of the sort field in the schema generation is currently incorrect. (Please correct me if I'm wrong.)

The custom AutoSchema class calls self._get_sort_parameters(path, method) for all GET & HEAD requests:

if method in ["GET", "HEAD"]:
    ...
    parameters += self._get_sort_parameters(path, method)
    ...

(Issue 1) The JSON:API spec says, "A server MAY choose to support requests to sort resource collections according to one or more criteria (“sort fields”)." The way that this is currently handled will naively add the sort query parameter irrespective of whether or not rest_framework_json_api.filters.OrderingFilter is enabled. Also, this will add a sort query parameter for requests for single resources as well (though I think DRF also does this).

(Issue 2) The Django REST Framework's OrderingFilter class implements a method for get_schema_operation_parameters that will also add a sort query parameter to the schema for the operation. This leads to duplicate sort query parameters listed for the operation.

def get_schema_operation_parameters(self, view):
        return [
            {
                'name': self.ordering_param,
                'required': False,
                'in': 'query',
                'description': force_str(self.ordering_description),
                'schema': {
                    'type': 'string',
                },
            },
        ]

Current Workaround

I've currently worked around this by overriding the OrderingFilter class:

from rest_framework_json_api.filters import OrderingFilter as DJAOrderingFilter

class OrderingFilter(DJAOrderingFilter):
    def get_schema_operation_parameters(self, view):
        return [{"$ref": "#/components/parameters/sort"}]

...and the AutoSchema class:

from rest_framework_json_api.schemas.openapi import AutoSchema as DJAAutoSchema

class AutoSchema(DJAAutoSchema):
        def _get_sort_parameters(self, path, method):
            return []

...and configuring these in my REST_FRAMEWORK config so that the sort parameter is conditionally added based on whether or not the OrderingFilter is enabled, but still uses the schema provided by this lib. Just thought I'd include this as a potential fix to the problem. However, this patch will still include a sort query parameter for requests for single resources (mentioned above).

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions