1

I am using DjangoRestApi and while it works like a charm with queryset (orm-based) views, I am struggling to make views that use different back-end to behave same way orm-based views are. Notably I want to add filters and have them cast and validated automatically.

Pseudo code below:

class NewsFilter(django_filters.FilterSet):
    category = django_filters.NumberFilter(name='category')
    limit = django_filters.NumberFilter(name='limit')
    page = django_filters.NumberFilter(name='page')


class NewsView(generics.APIView):
    filter_class = NewsFilter

    def get(self, request):
        filters = self.filter_class(??)  # not sure, what to put here

        payload = logic.get_business_news(**filters.data)  # same

        return Response(payload, status=status.HTTP_200_OK)

Any hint how to tackle problem will be appreciated.

Ultimate goal is to:

  • user types something into url or sends via POST, django-rest intercepts relevant values, extracts them, casts them into correct type and return as a dictionary
  • filters are displayed as they would if serializer was ORM based

1 Answer 1

1

The function signature to any single filter is like

class MyFilter(django_filters.Filter):
    def filter(self,queryset,value):
        [...]

The function signature to a FilterSet is:

def __init__(self, data=None, queryset=None, prefix=None, strict=None):

So, it looks like you pass in request.GET as data param and then pass in your queryset.

Sign up to request clarification or add additional context in comments.

6 Comments

I have slightly edited original question to clarify what I am looking for, as this answer is a) very incomplete and b) I have this feeling that don't answer my question
Fundamentally, FilterSet operates on querysets. Do you have a query set that you're filtering down? If not, you can't use FilterSet.
I don't want to work with queryset as I don't use ORM, what I do want is to render form in /api/ endpoint so that developers and other non-so-techy guys could test/work with api without manually typing json payload and so on. I started to figured out that django-rest-framework is actually very limited framework, with only one workflow in mind. :/
Ah true. It really is mostly a backend for talking with machines. You would normally write your frontend as a javascript client.
I should add that DRF is only an addendum to Django. You can use DRF side-by-side with Django in the same app.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.