Home > front end >  Django query to filter date range
Django query to filter date range

Time:09-02

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= 
                                                       [validate_range_date_time])

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(start_end_date__contains=timezone.now()   timezone.timedelta(days=90))

timezone.now()   timezone.timedelta(days=90) = datetime.datetime(2022, 11, 29, 22, 52, 7, 759648)

the query is giving empty set

CodePudding user response:

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)

CodePudding user response:

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
    )
)

CodePudding user response:

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!

  • Related