Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: timezone.now() does not return current datetime

Through a Django Rest Framework API, I am trying to serve all objects with a datetime in the future.

Problem is, once the server has started up, every time I submit the query, the API will serve all objects whose datetime is greater than the datetime at which the server started instead of the objects whose datetime is greater than the current time.

from django.utils import timezone

class BananasViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = Banana.objects.filter(date_and_time__gte=timezone.now())
    ...

Without any more luck, I also tried this variation:

import datetime as dt

class BananasViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = Banana.objects.filter(date_and_time__gte=
        timezone.make_aware(dt.datetime.now(), timezone.get_current_timezone())
    ...

Making a similar query in a Django shell correctly returns the objects up to date...

like image 207
Arnaud Renaud Avatar asked Apr 07 '26 08:04

Arnaud Renaud


1 Answers

As the application code is currently written you're running timezone.now() once, when the class is first imported from anywhere.

Rather than apply the time queryset filtering on the class attribute itself, do so in the get_queryset() method so that it'll be re-evaluated on each pass.

Eg.

class BananasViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = Banana.objects.all()

    def get_queryset(self):
        cutoff = timezone.now()
        return self.queryset.filter(date_and_time__gte=cutoff)
like image 67
Tom Christie Avatar answered Apr 10 '26 01:04

Tom Christie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!