Eldamir
Eldamir

Reputation: 10062

Django rest framework custom ordering field

I have enabled ordering on my API, and it works just fine. My problem is that it only allows me to order by fields values. I want to be able to make a query like

GET /api/some_endpoint/?crazy_query=123

and then, even though the model has no field crazy_field, I want to be able to respond to it somehow. I just don't know where do do it. The OrderingFilter is currently injected into all my viewsets by use of setting DEFAULT_FILTER_BACKENDS. I guess I would have to create a custom filter backend, but I'm unsure how to go about it

Upvotes: 4

Views: 4533

Answers (1)

djangonaut
djangonaut

Reputation: 7778

You can add your custom filter backend class anywhere you like. E.g. in

restframework_filters/CrazyBackend.py:

class CrazyBackend(filters.BaseFilterBackend):
    """
    My crazy filter.
    """
    def filter_queryset(self, request, queryset, view):
        crazy = request.query_params.get('crazy_query', None)
        if crazy:
            queryset = queryset.filter(...something crazy...)
        return queryset

Then add it to the settings:

REST_FRAMEWORK = {
    ...
    'DEFAULT_FILTER_BACKENDS': (
        'restframework_filters.CrazyBackend', ...
    ),

Don't forget the empty __init__.py in the new folder.

Upvotes: 4

Related Questions