Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 954
sush Avatar asked May 23 '11 19:05

sush


People also ask

What is Django Q?

Django Q is a native Django task queue, scheduler and worker application using Python multiprocessing.

What is Django filter?

Django-filter is a generic, reusable application to alleviate writing some of the more mundane bits of view code. Specifically, it allows users to filter down a queryset based on a model's fields, displaying the form to let them do this.


1 Answers

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))
like image 195
Chris Pratt Avatar answered Sep 20 '22 01:09

Chris Pratt