sush
sush

Reputation: 6077

django : Model filter on date ranges

How to get model filter on date ranges. In my project using employee doj, i need to deign a table. like employee who have joined less than three months , 3-6month, 6-12 months, 12-24 months.

Depart  < 3month  3-6months   6-12months  12-24months
----------------------------------------- ---- -----
  A dep   4        6             6           8

------------------------------------------------------

How to do this filter in django.

I have gone through this link ,but its confusing .

http://www.nerdydork.com/django-filter-model-on-date-range.html

Thanks in Advance

Upvotes: 6

Views: 5034

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239200

The range filter works like this:

MyModel.objects.filter(date__range=(range_start, range_end))

You can use that in conjunction with datetime.timedelta to get month periods. For example:

from datetime import datetime, timedelta

now = datetime.now()

# <3 months
three_months_ago = now - timedelta(months=3)
MyModel.objects.filter(date__range=(three_months_ago, now))

Upvotes: 20

Related Questions