Django: Filter Model on Date Range
Photo by Eliza Diamond on Unsplash
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 = date.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.year9 month = today.month - 110 if month == 0:11 month = 1212 year = year - 113 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 trans19 else:20 trans = trans.filter(date__year=today.year, date__month=today.month)21 return trans2223def filter_trans_days(trans, today, days):24 days = timedelta(days=days)25 begin = today - days26 return trans.filter(date__range=(begin, today))