Python Django Filter Date Range Example

Published On: 16/08/2022 | Category: Django

Hi Dev,

This post will give you example of python django filter date range example. it's simple example of django filter date. I’m going to show you about django filter datetime field by date. it's simple example of django filter by date. Let's get started with django date range filter.

Now, in this example demonstration, we will get all the students records where the joining date is between “2022-05-25” and “2022-06-07” (yyyy-mm-dd). Here is the code of the example.

In this example, we are using the following Student model. And this model has the following data.

Follow bellow tutorial step of python django filter date range example.

Student Admin Interface: Example

We are using the range field lookup to select all the database objects where the joining date is between “2022-05-25” and “2022-06-07”.

python manage.py shell

Now, we will execute the following example.

>>> from myApp.models import Student
>>>
>>> queryset = Student.objects.filter(joining_date__range=["2022-05-25","2022-06-07"]).values()
>>> 
>>> print(queryset)
Output
[
    {
        'id': 1,
        'name': 'Sonagra Bhavesh',
        'email': '[email protected]',
        'joining_date': datetime.date(2022, 5, 25)
    },
    {
        'id': 3,
        'name': 'Bhavesh',
        'email': '[email protected]',
        'joining_date': datetime.date(2022, 6, 7)
    },
    {
        'id': 4,
        'name': 'Vishal',
        'email': '[email protected]',
        'joining_date': datetime.date(2022, 5, 25)
    },
]

I Hope It will help you....