Reputation: 211
I have Django API built in and I have endpoint the return all object. I want the user to provide me with keyword to filter this queryset. What is the best way to do it. and how to do it plz ?
is it in get_queryset? if yes can you help me !?
Upvotes: 6
Views: 4085
Reputation: 121
just give pass the parameter with some default value:
def get_queryset(self, some_thing=default):
.
.
.
It will work
Upvotes: 0
Reputation: 476750
You have access to the GET parameters (in the querystring) with self.request.GET
[Django-doc].
So for example if there is a parameter ?category=foo
, you can access foo with self.request.GET['category']
, or self.request.GET.get('category')
if you want it to return None
in case it is missing.
You thus can filter for example with:
from rest_framework import generics
from app.models import SomeModel
from app.serializers import SomeSerializer
class UserList(generics.ListAPIView):
model = SomeModel
def get_queryset(self):
qs = super().get_queryset()
category = self.request.GET.get('category')
if category is None:
return qs
return qs.filter(category=categry)
Upvotes: 5