Skip to content

Instantly share code, notes, and snippets.

@peterfarrell
Created November 2, 2018 15:41
Show Gist options
  • Save peterfarrell/5c7b8d80319563813caba6320b568829 to your computer and use it in GitHub Desktop.
Save peterfarrell/5c7b8d80319563813caba6320b568829 to your computer and use it in GitHub Desktop.
Django Postgresql DateRange / DateTimeRange upper_inf and lower_inf functions
from django.db.models.lookups import Lookup
class DateRangeLowerInf(Lookup):
"""
Use like:
`MyObject.objects.filter(date_range__lower_inf=True)` for infinity
`MyObject.objects.filter(date_range__lower_inf=False)` for not infinity
"""
lookup_name = 'lower_inf'
prepare_rhs = False
def as_sql(self, compiler, connection):
sql, params = compiler.compile(self.lhs)
if self.rhs:
return "upper_inf(%s)" % sql, params
else:
return "upper_inf(%s) IS FALSE" % sql, params
class DateRangeUpperInf(Lookup):
"""
Use like:
`MyObject.objects.filter(date_range__upper_inf=True)` for infinity
`MyObject.objects.filter(date_range__upper_inf=False)` for not infinity
"""
lookup_name = 'upper_inf'
prepare_rhs = False
def as_sql(self, compiler, connection):
sql, params = compiler.compile(self.lhs)
if self.rhs:
return "upper_inf(%s)" % sql, params
else:
return "upper_inf(%s) IS FALSE" % sql, params
@peterfarrell
Copy link
Author

peterfarrell commented Nov 2, 2018

Additional functions that need to be implemented:

  • isempty
  • lower_inc
  • upper_inc

https://www.postgresql.org/docs/9.3/static/functions-range.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment