Return Upper Date in DateTimeTZRange

I have a model where i have a field called date range. which returns a range of date range both the date range is same but the time changes how can i access one date from range in the model using ORM.

class My_model(models.Model):
     date_range = ranges.DateTimeTZRange()

It looks like it can be accessed with upper and lower

obj = My_model.objects.all().first()
obj.date_range.upper
obj.date_range.lower

That field also inherents from RangeField It's all in contrib\postgres\fields\ranges.py if that helps at all

And here's some Query Stuff I you need: https://docs.djangoproject.com/en/3.2/ref/contrib/postgres/fields/#querying-range-fields


Edit, Aggregate

Source: Django/Postgres: Aggregate on RangeField

from django.db.models.functions import Upper, Lower
aggrDict = My_model.objects.all().aggregate(
    low=Min(Lower('date_range')),
    high=Max(Upper('date_range'))
)
print(aggrDict['low'])
print(aggrDict['high'])

Edit 2, filter

If you just want to return items that are 20 days away you could do:

from datetime import datetime, timedelta
twenty_days_in_the_future = (datetime.now()+timedelta(days=20)).date()

from django.db.models import Case, When, Value, IntegerField
My_model.objects.filter(date_range__lower=twenty_days_in_the_future)


# It might need a __date, idk
My_model.objects.filter(date_range__lower__date=twenty_days_in_the_future)
Back to Top