How to get queryset in django?

I am trying to send an email to those orders that is created 5 minutes before the datetime.now(). I try to filter the orders but it is not working, it is not giving me any queryset. How to do this? I am sharing my code.

def my_email(): 
    now = datetime.now() - timedelta(minutes=5) # 11:55
    now = now.replace(tzinfo=pytz.utc)
    print(now)
    order = Order.objects.filter(createdAt__gt = now)
    print(order)
    for o in order:
        print(o._id)

Upvotes: 1

Views: 260

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476557

You should not replace the timezone with UTC. now() will obtain the current datetime for a given timezone. If you replace that with UTC, then the result can be several hours ahead or behind the current time.

It might also be better to make use of a Now() expression [Django-doc], which will use the clock of the database, we thus can filter with:

from django.db.models.functions import Now
from datetime import timedelta

order = Order.objects.filter(createdAt__gt=Now()-timedelta(minutes=5))

If you plan to run this to send emails for orders the last five minutes, this will however be quite error-prone: since a scheduled task can always have a few milliseconds of delay, it thus means that certain items can, by the time the query is running, be considered too old. You probably might want to use a BooleanField that indicates if an email has been sent.

Upvotes: 2

Related Questions