Last active
March 6, 2018 16:16
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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