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

Time:04-02

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.

CodePudding user response:

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')
  • Related