[Answered ]-Django query to filter date range

1πŸ‘

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

Mymodel.objects.filter(
    start_end_date__contained_by=DateTimeTZRange(
        timezone.now(),
        timezone.now() + 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.

edited:

from psycopg2.extras import DateTimeTZRange

Mymodel.objects.filter(
    start_end_date__contained_by=DateTimeTZRange(
        timezone.now(),
        timezone.now() + timezone.timedelta(days=90),
    start_end_date__lower_inc=False
    )
)

1πŸ‘

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

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

Hope it helps!

-1πŸ‘

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.now() + timezone.timedelta(days=90)
MyModel.objects.filter(start_date__lte = target_time).filter(end_date__gte = target_time)

Leave a comment