Changes between Initial Version and Version 1 of Ticket #27147, comment 8


Ignore:
Timestamp:
Aug 1, 2018, 7:35:40 AM (6 years ago)
Author:
Jakub Skałecki

Legend:

Unmodified
Added
Removed
Modified
  • Ticket #27147, comment 8

    initial v1  
    33{{{
    44# db_utils.py
     5import sys
     6from datetime import timedelta
    57from functools import partial, wraps
    68from django.contrib.postgres.fields import ranges
    79
    810
    9 def create_bounded_range_field(cls):
    10     def init_wrapper(f):
    11         @wraps(f)
     11def create_bounded_range_field(cls, unit_diff):
     12    class RangeField(cls):
    1213        def __init__(self, *args, **kwargs):
    13             if 'bounds' in kwargs:
    14                 self.range_type = partial(self.range_type, bounds=kwargs.pop('bounds'))
    15             f(self, *args, **kwargs)
    16         return __init__
    17     cls.__init__ = init_wrapper(cls.__init__)
    18     return cls
     14            self.bounds = kwargs.pop('bounds', '[)')
     15            self.range_type = partial(self.range_type, bounds=self.bounds)
     16            super(RangeField, self).__init__(*args, **kwargs)
     17
     18        def from_db_value(self, value, expression, connection):
     19            # we're checking if bounds differ from default value
     20            # it's needed, because psycopg2 always returns Range with '[)' bounds
     21            if self.bounds[0] == '(':
     22                value._lower = value._lower - unit_diff
     23            if self.bounds[1] == ']':
     24                value._upper = value._upper - unit_diff
     25            value._bounds = self.bounds
     26            return value
    1927
    2028
    21 DateRangeField = create_bounded_range_field(ranges.DateRangeField)
    22 DateTimeRangeField = create_bounded_range_field(ranges.DateTimeRangeField)
    23 BigIntegerRangeField = create_bounded_range_field(ranges.BigIntegerRangeField)
    24 FloatRangeField = create_bounded_range_field(ranges.FloatRangeField)
    25 IntegerRangeField = create_bounded_range_field(ranges.IntegerRangeField)
     29    RangeField.__name__ = cls.__name__
     30    return RangeField
    2631
     32
     33DateRangeField = create_bounded_range_field(ranges.DateRangeField, timedelta(days=1))
     34DateTimeRangeField = create_bounded_range_field(ranges.DateTimeRangeField, timedelta(milliseconds=1))
     35BigIntegerRangeField = create_bounded_range_field(ranges.BigIntegerRangeField, 1)
     36FloatRangeField = create_bounded_range_field(ranges.FloatRangeField, sys.float_info.min)
     37IntegerRangeField = create_bounded_range_field(ranges.IntegerRangeField, 1)
    2738}}}
    2839
Back to Top