Using the Django-Rest Framework framework, you can implement a variety of queries and sorts, but the time-interval query problem is not solved. Based on the ordering parameter, the following parameter can be used to filter query time:

http://127.0.0.1:8000/index?time=2020-01-01 12:00:00, the 2020-10-01 12:00:00

Of course, your time string needs to conform
YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]For the framework, how to construct interface logic?


You might think of it in
list(self, request, *args, **kwargs)To make a logical judgment similar to the following:
In fact, however, such additional filtering conditions are meaningless, as you have checked
listThe source code will find that its own access to the data is from
self.get_queryset(), so you have the following code block:

def get_queryset(self) :
    queryset = self.queryset
    try:
        tfs = self.request.query_params.get('time')
        if tfs:
            start, stop = str(tfs).split(', ')
            if start and stop:
                queryset = queryset.filter(Q(time__gte=start) & Q(time__lte=stop))
            elif start:
                queryset = queryset.filter(time__gte=start)
            elif stop:
                queryset = queryset.filter(time__lte=stop)
    except (Exception,):
        raise exceptions.ParseError('time value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.')
    return queryset
Copy the code

Of course, your request method doesn’t need to do any more work, and it is recommended to refine the exceptions caught, returning different states and messages for different errors.





Bells and whistles