How to filter a queryset of objects created less than n hours ago from now with Django ?


Examples of how to filter a queryset of objects created less than n hours ago from now with Django

Filter a queryset (Example 1)

Filter a queryset of objects created less than 1 hour ago from now

time_threshold = datetime.datetime.now(timezone.utc) - datetime.timedelta(hours=1)

query = Article.objects.filter(date_created__gt=time_threshold)

Check the number of new entries (Example 2)

Example using a filter to check the number of new articles created by users in the last hour (lets assume that less that 20 new articles created in one hour seems normal but more can be suspicious)

models.py

class Article(models.Model):
    ...
    date_created = models.DateTimeField(default=datetime.now)   
    ...

views.py

time_threshold = datetime.datetime.now(timezone.utc) - datetime.timedelta(hours=1)
results = Article.objects.filter(date_created__gt=time_threshold)
if results.count() < 20:
    print('Looks ok  !')
else:
    print('somehting wrong !')

References