Django query to filter date range

I have a model which contains date range i want to filter the data based on the range date that is i want the data who's date range is 90 days from today's date.

class MyModel(models.Model):
    name = models.CharField(max_length=255)
    start_end_date = ranges.DateTimeRangeField(validators= 

so when we select the start date on page the end date will popoulate the same date but i cannot concatenate filter just by today date + timedelta(days=90) this is one single date and the field is date range, so how can i filter the date range data which is 90 days from now.

the model stores start_end_date as 'start_end_date': DateTimeTZRange(datetime.datetime(2022, 11, 29, 9, 15), datetime.datetime(2022, 11, 29, 10, 0),

Mymodel.objects.filter( + timezone.timedelta(days=90)) + timezone.timedelta(days=90) = datetime.datetime(2022, 11, 29, 22, 52, 7, 759648)

the query is giving empty set

I haven't used this field myself, but in base of what i read from documentaition, it should be like this:

from psycopg2.extras import DateTimeTZRange

    start_end_date__contained_by=DateTimeTZRange(, + timezone.timedelta(days=90)

to check if any start_end_date field is in 90 days from now, you should also pass a datetime range.

I think you could design the model more easily.

class MyModel(models.Model):
    name = models.CharField(max_length=255)
    start_date = models.DateTimeField()
    end_date = models.DateTimeField()

Then you can find objects like the following.

target_time = + timezone.timedelta(days=90)
MyModel.objects.filter(start_date__lte = target_time).filter(end_date__gte = target_time)

As it's a DateTimeRangeField, I think your result can be achieved by using startswith and endswith just like that:

max_date = + timezone.timedelta(days=90)
MyModel.objects.filter(, start_end_date__endswith__lte=max_date)

Hope it helps!

Back to Top