Prasiddha Pokhrel
Prasiddha Pokhrel

Reputation: 13

How to filter data between two dates in Django?

I am trying to develop a blood donation app. Here I need to get the donor's data which have last donated date more than 6 months ago that is if the donor has donated in last six months the donor's data should not be rendered to the template. I am trying to do that but could not figured out to do. So if anyone can help me then thank you in advance. Here is a column in models.py

lastDonatedDate = models.DateField(blank=True, null=True)

I just need to filter the donor's detail from the current date and the difference between two dates should be greater than 6 months.

Upvotes: 1

Views: 132

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476493

You can work with a __range lookup [Django-doc]:

MyModel.objects.filter(
    lastDonateDate__range=('2021-01-01', '2021-03-01')
)

or if we want to filter six months ago, we can install the dateutil package [readthedocs] with:

pip3 install python-dateutil

and then filter with:

from django.utils.timezone import now
from dateutil.relativedelta import relativedelta

MyModel.objects.filter(
    lastDonateDate__lt=now()-relativedelta(months=6)
)

Note: normally the name of the fields in a Django model are written in snake_case, not PerlCase, so it should be: last_donated_date instead of lastDonatedDate.

Upvotes: 2

Related Questions