Django: Filter Model on Date Range

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):

def filter_trans(request, trans):
	today = date.today()
	if 'filter' in request.POST:
		fltr = request.POST['filter']
		if fltr == 'this_month':
			trans = trans.filter(date__year=today.year, date__month=today.month)
		elif fltr == 'last_month':
			year = today.year
			month = today.month - 1
			if month == 0:
				month = 12
				year = year - 1
			trans = trans.filter(date__year=year, date__month=month)
		elif fltr[:4] == 'last':
			days = int(fltr[4:])
			trans = filter_trans_days(trans, today, days)
		elif fltr == 'all':
			return trans
	else:
		trans = trans.filter(date__year=today.year, date__month=today.month)
	return trans

def filter_trans_days(trans, today, days):
	days = timedelta(days=days)
	begin = today - days
	return trans.filter(date__range=(begin, today))

Related posts:

  1. Django & Djson… er, JSON I must admin this is my first attempt at even...
  2. Django: Login Form on Every Page Up to the point, when it has come to Django...
  3. Copy Model Object in Django I ran into a situation where I wanted to created...

Related posts brought to you by Yet Another Related Posts Plugin.

June 22, 2009  Tags: , ,   Posted in: Programming & Internet

Leave a Reply