Home > Enterprise >  Filter queryset by year between two date fields
Filter queryset by year between two date fields

Time:03-30

I have a start_date and an end_date fields in my model. The user shall be able to filter records by selecting a year value, so that records that span over multiple years should be shown if the year selected is included.

For example: Selected year: 2019

start_date end_date
2017-03-12 2021-09-03
2019-12-12 2020-06-05

I can do this query by raw SQL like that:

SELECT * FROM `orders` WHERE '2019' BETWEEN YEAR(`start_date`) AND YEAR(`end_date`);

How can I do this using Django ORM and avoid raw SQL queries? Because I am already using the ORM in multiple filters and only remaining this bit.

CodePudding user response:

in views.py:

from django.db.models import Q

YourModel.objects.filter(
    Q(start_date__year=2019) |
    Q(end_date__year=2019)
)

CodePudding user response:

Try this:

YourModel.objects.filter(
    start_date__year__lte=2019, 
    end_date__year__gte=2019,
)
  • Related