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

Active January 05, 2021    /    Viewed 8830    /    Comments 0    /    Edit


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


Card image cap
profile-image
Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!



Did you find this content useful ?, If so, please consider donating a tip to the author(s). MoonBooks.org is visited by millions of people each year and it will help us to maintain our servers and create new contents.

Amount