Skip to content

Instantly share code, notes, and snippets.

@jackton1
Last active March 6, 2018 16:16
Show Gist options
  • Save jackton1/8d33a3ad6198b4be15c55dedb0382fae to your computer and use it in GitHub Desktop.
Save jackton1/8d33a3ad6198b4be15c55dedb0382fae to your computer and use it in GitHub Desktop.
Extending django_filters DateTimeFromToRangeFilter to support postgres datetime tstzrange fields with the available lookup names.
from django.contrib.postgres.forms import DateTimeRangeField
from django.core.exceptions import ImproperlyConfigured
from django_filters import DateTimeFromToRangeFilter as DateTimeFromToRangeGenericFilter
class DateTimeTZFromToRangeFilter(DateTimeFromToRangeGenericFilter):
field_class = DateTimeRangeField
lookup_names = {
'contained_by', 'contains', 'overlap', 'fully_lt', 'full_gt',
'not_lt', 'not_gt', 'adjacent_to',
}
default_lookup_expr = 'contained_by'
def _get_lookup_expr(self):
if self.lookup_expr in self.lookup_names:
return self.lookup_expr
raise ImproperlyConfigured(
f'{self.__class__.__name__} "lookup_expr" has to be one of '
f'"{repr(self.lookup_names)}".',
)
def filter(self, qs, value):
if value:
qs = self.get_method(qs)
lookup = f'{self.field_name}'
if all([value.lower is not None, value.upper is not None]):
lookup += f'__{self._get_lookup_expr()}'
else:
if value.lower is not None:
lookup += '__not_lt'
if value.upper is not None:
lookup += '__not_gt'
qs = qs(**{lookup: value})
if self.distinct:
qs = qs.distinct()
return qs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment