How to filter a queryset of objects created more than one hour ago from Django's DateTimeField?

Issue

Problem:

I’m trying to filter a model where the status has not changed in over an hour.

What I’ve tried:

Product.objects.filter(
                Q(status="PENDING"),
                Q(created__hour__gt=1)
            ).all().order_by("-created")

Expected Solution:
Get a queryset of objects whose status is "PENDING" but has not changed in more than one hour.

Solution

You filter with:

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

Product.objects.filter(
    status="PENDING", created__lt=Now()-timedelta(hours=1)
).order_by('-created')

Answered By – Willem Van Onsem

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published