[Answer]-Django – filtering url responses

1👍

Usually the GET parameters are passed in a dictionary attached to the request object. See the documentation on request objects.

Try:

Date = self.request.GET.get('Date')
👤Aurora

0👍

‘Date’ in your case is not a keyword argument but a query parameter.
I would do that like this:

# first import the needed modules, classes, functions, ...
import re
from django.http import Http404


class File_List(generics.ListAPIView):
    serializer_class = CDX_compositesSerializer

    def get_queryset(self):
        queryset = cdx_composites_csv.objects.using('markit').all()
        # get the query parameter or None in case it is empty
        date = self.request.QUERY_PARAMS.get('Date', None)
        # regex for correct date
        regex_date = re.compile(r'^\d{4}-\d{2}-\d{2}$')
        # filter your queryset if you really got a correct date
        if date is not None and regex_date.match(date):
            queryset = queryset.filter(Date__contains=date)
        # if there are no results return 404 NOT FOUND
        if not queryset:
            raise Http404
        return queryset

Perhaps there are better solutions, but this should work. Remember always to check the user input.

I don’t know your model, but maybe you could implement a manager that would return all objects using ‘markit’.
Than you could get the queryset like this (just a possible example):

queryset = cdx_composites_csv.markit.all()

Here ‘markit’ is an attribute in your model holding your custom manager:

MarkitManager(models.Manager):
    def get_query_set(self):
        return Super(MarkitManager, self).get_query_set().using('markit')

More about filtering against query parameters can be found in the official documentation of DRF:
http://www.django-rest-framework.org/api-guide/filtering#filtering-against-query-parameters

👤cezar

Leave a comment