2017-02-08 01:46:18 +08:00
|
|
|
import datetime
|
2015-01-11 00:14:20 +08:00
|
|
|
import json
|
|
|
|
|
2015-01-28 20:35:27 +08:00
|
|
|
from psycopg2.extras import DateRange, DateTimeTZRange, NumericRange, Range
|
|
|
|
|
|
|
|
from django.contrib.postgres import forms, lookups
|
2015-01-11 00:14:20 +08:00
|
|
|
from django.db import models
|
|
|
|
|
2015-06-06 19:55:04 +08:00
|
|
|
from .utils import AttributeSetter
|
|
|
|
|
2015-01-11 00:14:20 +08:00
|
|
|
__all__ = [
|
|
|
|
'RangeField', 'IntegerRangeField', 'BigIntegerRangeField',
|
2018-10-03 07:17:23 +08:00
|
|
|
'DecimalRangeField', 'DateTimeRangeField', 'DateRangeField',
|
|
|
|
'FloatRangeField',
|
2015-01-11 00:14:20 +08:00
|
|
|
]
|
|
|
|
|
|
|
|
|
|
|
|
class RangeField(models.Field):
|
|
|
|
empty_strings_allowed = False
|
|
|
|
|
2016-04-03 18:39:18 +08:00
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
# Initializing base_field here ensures that its model matches the model for self.
|
|
|
|
if hasattr(self, 'base_field'):
|
|
|
|
self.base_field = self.base_field()
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__init__(*args, **kwargs)
|
2016-04-03 18:39:18 +08:00
|
|
|
|
|
|
|
@property
|
|
|
|
def model(self):
|
|
|
|
try:
|
|
|
|
return self.__dict__['model']
|
|
|
|
except KeyError:
|
|
|
|
raise AttributeError("'%s' object has no attribute 'model'" % self.__class__.__name__)
|
|
|
|
|
|
|
|
@model.setter
|
|
|
|
def model(self, model):
|
|
|
|
self.__dict__['model'] = model
|
|
|
|
self.base_field.model = model
|
|
|
|
|
2015-01-11 00:14:20 +08:00
|
|
|
def get_prep_value(self, value):
|
|
|
|
if value is None:
|
|
|
|
return None
|
|
|
|
elif isinstance(value, Range):
|
|
|
|
return value
|
|
|
|
elif isinstance(value, (list, tuple)):
|
|
|
|
return self.range_type(value[0], value[1])
|
|
|
|
return value
|
|
|
|
|
|
|
|
def to_python(self, value):
|
2016-12-29 23:27:49 +08:00
|
|
|
if isinstance(value, str):
|
2015-06-06 19:55:04 +08:00
|
|
|
# Assume we're deserializing
|
|
|
|
vals = json.loads(value)
|
|
|
|
for end in ('lower', 'upper'):
|
|
|
|
if end in vals:
|
|
|
|
vals[end] = self.base_field.to_python(vals[end])
|
|
|
|
value = self.range_type(**vals)
|
2015-01-11 00:14:20 +08:00
|
|
|
elif isinstance(value, (list, tuple)):
|
|
|
|
value = self.range_type(value[0], value[1])
|
|
|
|
return value
|
|
|
|
|
2015-06-06 19:55:04 +08:00
|
|
|
def set_attributes_from_name(self, name):
|
2017-01-21 21:13:44 +08:00
|
|
|
super().set_attributes_from_name(name)
|
2015-06-06 19:55:04 +08:00
|
|
|
self.base_field.set_attributes_from_name(name)
|
|
|
|
|
2015-01-11 00:14:20 +08:00
|
|
|
def value_to_string(self, obj):
|
2015-04-26 14:30:46 +08:00
|
|
|
value = self.value_from_object(obj)
|
2015-01-11 00:14:20 +08:00
|
|
|
if value is None:
|
|
|
|
return None
|
|
|
|
if value.isempty:
|
|
|
|
return json.dumps({"empty": True})
|
2015-06-06 19:55:04 +08:00
|
|
|
base_field = self.base_field
|
|
|
|
result = {"bounds": value._bounds}
|
|
|
|
for end in ('lower', 'upper'):
|
2016-02-16 02:28:49 +08:00
|
|
|
val = getattr(value, end)
|
|
|
|
if val is None:
|
|
|
|
result[end] = None
|
|
|
|
else:
|
|
|
|
obj = AttributeSetter(base_field.attname, val)
|
|
|
|
result[end] = base_field.value_to_string(obj)
|
2015-06-06 19:55:04 +08:00
|
|
|
return json.dumps(result)
|
2015-01-11 00:14:20 +08:00
|
|
|
|
|
|
|
def formfield(self, **kwargs):
|
|
|
|
kwargs.setdefault('form_class', self.form_field)
|
2017-01-21 21:13:44 +08:00
|
|
|
return super().formfield(**kwargs)
|
2015-01-11 00:14:20 +08:00
|
|
|
|
|
|
|
|
|
|
|
class IntegerRangeField(RangeField):
|
2016-04-03 18:39:18 +08:00
|
|
|
base_field = models.IntegerField
|
2015-01-11 00:14:20 +08:00
|
|
|
range_type = NumericRange
|
|
|
|
form_field = forms.IntegerRangeField
|
|
|
|
|
|
|
|
def db_type(self, connection):
|
|
|
|
return 'int4range'
|
|
|
|
|
|
|
|
|
|
|
|
class BigIntegerRangeField(RangeField):
|
2016-04-03 18:39:18 +08:00
|
|
|
base_field = models.BigIntegerField
|
2015-01-11 00:14:20 +08:00
|
|
|
range_type = NumericRange
|
|
|
|
form_field = forms.IntegerRangeField
|
|
|
|
|
|
|
|
def db_type(self, connection):
|
|
|
|
return 'int8range'
|
|
|
|
|
|
|
|
|
2018-10-03 07:17:23 +08:00
|
|
|
class DecimalRangeField(RangeField):
|
|
|
|
base_field = models.DecimalField
|
|
|
|
range_type = NumericRange
|
|
|
|
form_field = forms.DecimalRangeField
|
|
|
|
|
|
|
|
def db_type(self, connection):
|
|
|
|
return 'numrange'
|
|
|
|
|
|
|
|
|
2015-01-11 00:14:20 +08:00
|
|
|
class FloatRangeField(RangeField):
|
2018-10-03 07:17:23 +08:00
|
|
|
system_check_deprecated_details = {
|
|
|
|
'msg': (
|
|
|
|
'FloatRangeField is deprecated and will be removed in Django 3.1.'
|
|
|
|
),
|
|
|
|
'hint': 'Use DecimalRangeField instead.',
|
|
|
|
'id': 'fields.W902',
|
|
|
|
}
|
2016-04-03 18:39:18 +08:00
|
|
|
base_field = models.FloatField
|
2015-01-11 00:14:20 +08:00
|
|
|
range_type = NumericRange
|
|
|
|
form_field = forms.FloatRangeField
|
|
|
|
|
|
|
|
def db_type(self, connection):
|
|
|
|
return 'numrange'
|
|
|
|
|
|
|
|
|
|
|
|
class DateTimeRangeField(RangeField):
|
2016-04-03 18:39:18 +08:00
|
|
|
base_field = models.DateTimeField
|
2015-01-11 00:14:20 +08:00
|
|
|
range_type = DateTimeTZRange
|
|
|
|
form_field = forms.DateTimeRangeField
|
|
|
|
|
|
|
|
def db_type(self, connection):
|
|
|
|
return 'tstzrange'
|
|
|
|
|
|
|
|
|
|
|
|
class DateRangeField(RangeField):
|
2016-04-03 18:39:18 +08:00
|
|
|
base_field = models.DateField
|
2015-01-11 00:14:20 +08:00
|
|
|
range_type = DateRange
|
|
|
|
form_field = forms.DateRangeField
|
|
|
|
|
|
|
|
def db_type(self, connection):
|
|
|
|
return 'daterange'
|
|
|
|
|
|
|
|
|
|
|
|
RangeField.register_lookup(lookups.DataContains)
|
|
|
|
RangeField.register_lookup(lookups.ContainedBy)
|
|
|
|
RangeField.register_lookup(lookups.Overlap)
|
|
|
|
|
|
|
|
|
2017-02-08 01:46:18 +08:00
|
|
|
class DateTimeRangeContains(models.Lookup):
|
|
|
|
"""
|
|
|
|
Lookup for Date/DateTimeRange containment to cast the rhs to the correct
|
|
|
|
type.
|
|
|
|
"""
|
|
|
|
lookup_name = 'contains'
|
|
|
|
|
|
|
|
def process_rhs(self, compiler, connection):
|
|
|
|
# Transform rhs value for db lookup.
|
|
|
|
if isinstance(self.rhs, datetime.date):
|
|
|
|
output_field = models.DateTimeField() if isinstance(self.rhs, datetime.datetime) else models.DateField()
|
|
|
|
value = models.Value(self.rhs, output_field=output_field)
|
|
|
|
self.rhs = value.resolve_expression(compiler.query)
|
|
|
|
return super().process_rhs(compiler, connection)
|
|
|
|
|
|
|
|
def as_sql(self, compiler, connection):
|
|
|
|
lhs, lhs_params = self.process_lhs(compiler, connection)
|
|
|
|
rhs, rhs_params = self.process_rhs(compiler, connection)
|
|
|
|
params = lhs_params + rhs_params
|
|
|
|
# Cast the rhs if needed.
|
|
|
|
cast_sql = ''
|
|
|
|
if isinstance(self.rhs, models.Expression) and self.rhs._output_field_or_none:
|
|
|
|
cast_internal_type = self.lhs.output_field.base_field.get_internal_type()
|
|
|
|
cast_sql = '::{}'.format(connection.data_types.get(cast_internal_type))
|
|
|
|
return '%s @> %s%s' % (lhs, rhs, cast_sql), params
|
|
|
|
|
|
|
|
|
|
|
|
DateRangeField.register_lookup(DateTimeRangeContains)
|
|
|
|
DateTimeRangeField.register_lookup(DateTimeRangeContains)
|
|
|
|
|
|
|
|
|
2015-05-21 19:25:50 +08:00
|
|
|
class RangeContainedBy(models.Lookup):
|
|
|
|
lookup_name = 'contained_by'
|
|
|
|
type_mapping = {
|
|
|
|
'integer': 'int4range',
|
|
|
|
'bigint': 'int8range',
|
|
|
|
'double precision': 'numrange',
|
|
|
|
'date': 'daterange',
|
|
|
|
'timestamp with time zone': 'tstzrange',
|
|
|
|
}
|
|
|
|
|
|
|
|
def as_sql(self, qn, connection):
|
|
|
|
field = self.lhs.output_field
|
|
|
|
if isinstance(field, models.FloatField):
|
|
|
|
sql = '%s::numeric <@ %s::{}'.format(self.type_mapping[field.db_type(connection)])
|
|
|
|
else:
|
|
|
|
sql = '%s <@ %s::{}'.format(self.type_mapping[field.db_type(connection)])
|
|
|
|
lhs, lhs_params = self.process_lhs(qn, connection)
|
|
|
|
rhs, rhs_params = self.process_rhs(qn, connection)
|
|
|
|
params = lhs_params + rhs_params
|
|
|
|
return sql % (lhs, rhs), params
|
|
|
|
|
|
|
|
def get_prep_lookup(self):
|
2016-04-24 01:13:31 +08:00
|
|
|
return RangeField().get_prep_value(self.rhs)
|
2015-05-21 19:25:50 +08:00
|
|
|
|
|
|
|
|
|
|
|
models.DateField.register_lookup(RangeContainedBy)
|
|
|
|
models.DateTimeField.register_lookup(RangeContainedBy)
|
|
|
|
models.IntegerField.register_lookup(RangeContainedBy)
|
|
|
|
models.BigIntegerField.register_lookup(RangeContainedBy)
|
|
|
|
models.FloatField.register_lookup(RangeContainedBy)
|
|
|
|
|
|
|
|
|
2015-01-11 00:14:20 +08:00
|
|
|
@RangeField.register_lookup
|
|
|
|
class FullyLessThan(lookups.PostgresSimpleLookup):
|
|
|
|
lookup_name = 'fully_lt'
|
|
|
|
operator = '<<'
|
|
|
|
|
|
|
|
|
|
|
|
@RangeField.register_lookup
|
|
|
|
class FullGreaterThan(lookups.PostgresSimpleLookup):
|
|
|
|
lookup_name = 'fully_gt'
|
|
|
|
operator = '>>'
|
|
|
|
|
|
|
|
|
|
|
|
@RangeField.register_lookup
|
|
|
|
class NotLessThan(lookups.PostgresSimpleLookup):
|
|
|
|
lookup_name = 'not_lt'
|
|
|
|
operator = '&>'
|
|
|
|
|
|
|
|
|
|
|
|
@RangeField.register_lookup
|
|
|
|
class NotGreaterThan(lookups.PostgresSimpleLookup):
|
|
|
|
lookup_name = 'not_gt'
|
|
|
|
operator = '&<'
|
|
|
|
|
|
|
|
|
|
|
|
@RangeField.register_lookup
|
|
|
|
class AdjacentToLookup(lookups.PostgresSimpleLookup):
|
|
|
|
lookup_name = 'adjacent_to'
|
|
|
|
operator = '-|-'
|
|
|
|
|
|
|
|
|
|
|
|
@RangeField.register_lookup
|
2015-08-03 10:30:06 +08:00
|
|
|
class RangeStartsWith(models.Transform):
|
2015-01-11 00:14:20 +08:00
|
|
|
lookup_name = 'startswith'
|
|
|
|
function = 'lower'
|
|
|
|
|
|
|
|
@property
|
|
|
|
def output_field(self):
|
|
|
|
return self.lhs.output_field.base_field
|
|
|
|
|
|
|
|
|
|
|
|
@RangeField.register_lookup
|
2015-08-03 10:30:06 +08:00
|
|
|
class RangeEndsWith(models.Transform):
|
2015-01-11 00:14:20 +08:00
|
|
|
lookup_name = 'endswith'
|
|
|
|
function = 'upper'
|
|
|
|
|
|
|
|
@property
|
|
|
|
def output_field(self):
|
|
|
|
return self.lhs.output_field.base_field
|
|
|
|
|
|
|
|
|
|
|
|
@RangeField.register_lookup
|
2015-08-03 10:30:06 +08:00
|
|
|
class IsEmpty(models.Transform):
|
2015-01-11 00:14:20 +08:00
|
|
|
lookup_name = 'isempty'
|
|
|
|
function = 'isempty'
|
|
|
|
output_field = models.BooleanField()
|