Home > Mobile >  Querying for models based on time range in Django REST Framework
Querying for models based on time range in Django REST Framework

Time:05-20

I have a DB with models that each have two timestamps.

class Timespan(models.Model):
    name = models.CharField(null=False)
    start_time = models.DateTimeField(null=False)
    end_time = models.DateTimeField(null=False)

I want to be able to query for these objects based on a timestamp range. A GET request would also have a start and end time, and any Timespans that overlap would be returned.

However I'm not sure how to construct a GET Request to do this, nor the View in Django.

Should the GET request just use url parameters?

GET www.website.com/timespan?start=1000&end=1050

or pass it in the body? (if it even makes a difference)

My view currently looks like this:

class TimespanViewSet(OSKAuthMixin, ModelViewSet):
    queryset = Timespan.objects.filter()
    serializer_class = TimespanSerializer

Which allows me to return obj by ID GET www.website.com/timestamp/42.

I expect I'll need a new viewset for this query. I know how to add a ViewSet with a nested urlpath, but shouldn't there be a way to send a request to /timespan the inclusion of a "start" and "end" parameter changes what is returned?

CodePudding user response:

You can customize get_queryset function

from django.db.models import Q

class TimespanViewSet(OSKAuthMixin, ModelViewSet):
    queryset = Timespan.objects.filter()
    serializer_class = TimespanSerializer

    def get_queryset(self):
        start_timestamp = int(self.request.GET.get("start", "0"))
        end_timestamp = int(self.request.GET.get("end", "0"))
        
        if start_timestamp > 0 and start_timestamp > 0:
            return Timespan.objects.filter(
                Q(start_time___range = (start_timestamp, end_timestamp)) |
                Q(end_time___range = (start_timestamp, end_timestamp))
            )
        else:
            return Timespan.objects.all()

Hope it could help.

CodePudding user response:

you can do the conversion and many ways but I guess the easiest way is like this:

...    
from django.utils import timezone
...

class TimespanViewSet(OSKAuthMixin, ModelViewSet):
    queryset = Timespan.objects.all()
    serializer_class = TimespanSerializer
    def get_queryset(self,*args,**kwargs):
        start_time = self.request.GET.get("start_time",None)
        end_time = self.request.GET.get("end_time",None)
        if start_time and end_time :
            # convert timestamps to timezone objects
            start_time_instance = timezone.datetime.fromtimestamp(start_time)
            end_time_instance = timezone.datetime.fromtimestamp(end_time)
            return self.queryset.filter(start_time=start_time_instance,end_time_instance=end_time_instance)
        else:
            # do some handling here
            return self.queryset

            
  • Related