Search code examples
djangodjango-rest-frameworkdjango-filter

Passing a variable into a filter Django Rest Framework


I'm using a filter in my Django Rest Framework project to search for items in a given date range. I would like to pass variables into a url like so: /?start_date=2022-12-01&end_date=2022-12-06 but I can't seem to figure out how to insert 'start_date' and 'end_date' as variables you can search. The filter works when I do

queryset = Search.objects.filter(added_date__range=["2022-12-06", "2022-12-06"])

but I would like it to be something like:

queryset = Search.objects.filter(added_date__range=[start_date, end_date])

Here is the model:

class Search(models.Model):
    added_date = models.CharField(max_length=256)
    added_time = models.CharField(max_length=256)
    id = models.BigIntegerField()
    name = models.CharField(max_length=256)

View:

class SearchViewSet(generics.GenericAPIView):

    def get_queryset(self):
        try:
            Search.objects.filter(added_date__range=[self.start_date, self.end_date])
        except Exception as exception:
            return Response(response500('No Data Found', exception), status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    def get(self, request):
        self.start_date = request.GET['start_date']
        self.end_date = request.GET['end_date']

        try:
            queryset = self.get_queryset()
            search_data = SearchSerializer(queryset, many=True)
            resp = {'data': search_data.data}
            response = Response(resp)
            return response
        except Exception as exception:
            return Response(response500('No Data Found', exception), status=status.HTTP_500_INTERNAL_SERVER_ERROR)

Url:

re_path(r'search-summary', views.SearchViewSet.as_view(), name='search-summary')

Solution

  • In class based views, you can use self.request.query_params.get(). so, for example:

    def get_queryset(self):
        start_date= self.request.query_params.get('start_date')
        end_date = self.request.query_params.get('end_date')
        try:
            Search.objects.filter(added_date__range=[start_date, end_date])
        except Exception as exception:
            return Response(response500('No Data Found', exception), status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    

    If you need to use them elsewhere, then you should still be able to use the same method in get() to add them to self.