Home > Software engineering >  How to filter objects whose created_date exceeds 30 days
How to filter objects whose created_date exceeds 30 days

Time:07-13

Here,I have model

from django.db import models
class Product(models.Model):
     name=models.CharField(max_length=100)
     created_at=models.DateTimeField(auto_now_add=True)

I want to get all those objects that date exceeds 30 days from creation,by like this but this doesnot work.

Is there any way to hack this scenario

from django.db.models import  F
from django.utils import timezone

Product.objects.annotate(diff_date=(timezone.now()-F('created_at'))).filter(diff_date__days__gte=30)

CodePudding user response:

You don't need to annotate and filter, you can just set the filter to pick out dates that are before 30 days ago, like so:

from datetime import timedelta
from django.utils import timezone

thirty_days_ago = timezone.now() - timedelta(days=30)
Product.objects.filter(created_at__lte=thirty_days_ago)
  • Related