Using query strings in django GET
Question:
I’ve a GET request in django rest framework that fetches data using kwargs.
class FetchUser(APIView):
def get(self, request, **kwargs):
try:
email = kwargs.get('email')
user = User.objects.get(email=email)
return Response(UserSerializer(user).data, status=status.HTTP_200_OK)
except(KeyError, User.DoesNotExist) as e:
return Response(str(e), status=status.HTTP_404_NOT_FOUND)
Here’s my url
path(r'fetch/<str:email>', FetchUser.as_view(), name='fetch_user'),
However I want to fetch the data using a query string,
Something like http://base/fetch?email=something
How do I modify my urls and views to do this?
Answers:
You can do something like –
def get_queryset(self):
cityId = self.request.GET.get('city')
# this reads query param
if cityId is None:
queryset = branch.objects.all()
# queryset = branch.objects.none()
else:
queryset = branch.objects.filter(city=cityId)
return queryset
and your query can be
http://base/?city=something
The key here is to configure urls.py like this:
path('base/fetch/', FetchUser.as_view()),
Then, you will pass the parameters as query string on the URL, using ? and &:
http://base/fetch?param1=something¶m2=something_else
On your views.py, the query string parameters will be available in request.GET, and you can get them like this:
class FetchUser(APIView):
def get(self, request):
try:
param1 = request.GET.get('param1')
param2 = request.GET.get('param2')
...
I’ve a GET request in django rest framework that fetches data using kwargs.
class FetchUser(APIView):
def get(self, request, **kwargs):
try:
email = kwargs.get('email')
user = User.objects.get(email=email)
return Response(UserSerializer(user).data, status=status.HTTP_200_OK)
except(KeyError, User.DoesNotExist) as e:
return Response(str(e), status=status.HTTP_404_NOT_FOUND)
Here’s my url
path(r'fetch/<str:email>', FetchUser.as_view(), name='fetch_user'),
However I want to fetch the data using a query string,
Something like http://base/fetch?email=something
How do I modify my urls and views to do this?
You can do something like –
def get_queryset(self):
cityId = self.request.GET.get('city')
# this reads query param
if cityId is None:
queryset = branch.objects.all()
# queryset = branch.objects.none()
else:
queryset = branch.objects.filter(city=cityId)
return queryset
and your query can be
http://base/?city=something
The key here is to configure urls.py like this:
path('base/fetch/', FetchUser.as_view()),
Then, you will pass the parameters as query string on the URL, using ? and &:
http://base/fetch?param1=something¶m2=something_else
On your views.py, the query string parameters will be available in request.GET, and you can get them like this:
class FetchUser(APIView):
def get(self, request):
try:
param1 = request.GET.get('param1')
param2 = request.GET.get('param2')
...