Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django filter older than day(s)?

Tags:

django

The day is the number a user will input to get the result that is older than (days from user input). For example, if user inputs 32 days, they will get the results that are older than 30 days.

A quick try-out:

class Entry(models.Model):
    entered = models.DateTimeField()

>>> from datetime import datetime
>>> Entry(entered = datetime.now()).save()
>>> Entry.objects.filter(entered__lte = datetime.now())
[<Entry: Entry object>]
>>> Entry.objects.filter(entered__gte = datetime.now())
[]
>>> Entry.objects.filter(entered__gte = datetime.now(), entered__lte=datetime(2009,11,1,0,0))
[<Entry: Entry object>]

My problem and my trying

xxxx__day__lte.

last_contact_filled input from input field

for day_filter in xrange(1,int(last_contact_filled)+1):
                qdict['last_contact__day']=day_filter

What's the best way to do this in Django to filter by day(s) in my case?

like image 875
kn3l Avatar asked Dec 31 '09 05:12

kn3l


People also ask

What is the purpose of filter () method in django?

The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.

Does the order of filters matter in django?

It doesn't matter, the result will be the same.


3 Answers

Something like this would work for you:

from datetime import datetime, timedelta
how_many_days = 30
MyObject.objects.filter(entered__lte=datetime.now()-timedelta(days=how_many_days))
like image 191
kibitzer Avatar answered Oct 22 '22 02:10

kibitzer


we can use Django timezone.now() with timedelta

from datetime import timedelta
from django.utils import timezone
time_threshold = timezone.now() - timedelta(days=7)
Entry.objects.filter(entered__gte=time_threshold)
like image 21
Mani Avatar answered Oct 22 '22 02:10

Mani


Add a timedelta(-30) to the datetime in the filter.

like image 2
Ignacio Vazquez-Abrams Avatar answered Oct 22 '22 01:10

Ignacio Vazquez-Abrams