'Filter queryset by year between two date fields

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.



Solution 1:[1]

Try this:

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Brian Destura