简体   繁体   中英

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.

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

MyModel.objects.filter(
    
)

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

pip3 install 

and then filter with:

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

MyModel.objects.filter(
    
)

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM