This site runs best with JavaScript enabled.

Django: Filter Model on Date Range

A generic filter function to filter query results by data ranges

I'm sure this is in the documentation somewhere but it wasn't totally obvious to me and I knew there had to be an easy way to filter a model based on a date range. I'm in the process of filtering transactions for Inzolo and giving the user options for the following date filters:

  • Month to date
  • Last month
  • Past week
  • Past 2 weeks
  • Last 30 days
  • Last 60 days
  • Last 90 days
  • All transactions

There really is easy ways to do all of these, but they are slightly different. What I got hung up on was the range. My assumption would be to do something like .filter(date >= begin_date, date <= today) but that obviously won't work. I finally found what I needed with the range function.

So to get each of the filters to work, I created a filter function that looks like this (I'll let you read between the lines to figure out what it is doing):

1def filter_trans(request, trans):
2 today =
3 if 'filter' in request.POST:
4 fltr = request.POST['filter']
5 if fltr == 'this_month':
6 trans = trans.filter(date__year=today.year, date__month=today.month)
7 elif fltr == 'last_month':
8 year = today.year
9 month = today.month - 1
10 if month == 0:
11 month = 12
12 year = year - 1
13 trans = trans.filter(date__year=year, date__month=month)
14 elif fltr[:4] == 'last':
15 days = int(fltr[4:])
16 trans = filter_trans_days(trans, today, days)
17 elif fltr == 'all':
18 return trans
19 else:
20 trans = trans.filter(date__year=today.year, date__month=today.month)
21 return trans
23def filter_trans_days(trans, today, days):
24 days = timedelta(days=days)
25 begin = today - days
26 return trans.filter(date__range=(begin, today))

Discuss on TwitterEdit post on GitHub

Share article
Dustin Davis

Dustin Davis is a software engineer, people manager, hacker, and entreprenuer. He loves to develop systems and automation. He lives with his wife and five kids in Utah.

Join the Newsletter

Dustin Davis