python - Subclass timedelta within Django model field -


i have extended datetime.timedelta previous work update division operator support floats (not supported before python 3.x). having started using durationfield in 1 of models create custom version uses extended timedelta class objects returned after query include custom timedelta class. correct approach implement this?

i've been editing durationfield class whilst figure out how above before taking next step figure out how add custom model field. code follows (modified django source code:

class timedeltaextended(datetime.timedelta):     def __div__(self, divisor):         return timedeltaextended(seconds=self.total_seconds()/divisor)      def __mul__(self, multiplier):         return timedeltaextended(seconds=self.total_seconds()*multiplier)      def __add__(self, other):         if isinstance(other, int) , other 0:             return self         else:             datetime.timedelta.__add__(other)  class durationfield(field): ...      def to_python(self, value):         if value none:             return value         if isinstance(value, timedeltaextended):             return value         try:             parsed = parse_duration(value)         except valueerror:             pass         else:             if parsed not none:                 return parsed          raise exceptions.validationerror(             self.error_messages['invalid'],             code='invalid',             params={'value': value},         ) ... 

however when use code queries still return normal timedelta objects. area should looking at?

environment python 2.7, django 1.11

this how duration field parse serialised form of timedelta(seconds=123.456):

>>> durationfield().to_python('00:02:03.456000') datetime.timedelta(0, 123, 456000) 

you can let superclass heavy lifting of validation, exception handling, etc. convert specialised class post-processing step:

>>> class mydurationfield(durationfield): ...     def to_python(self, value): ...         timedelta = super(mydurationfield, self).to_python(value) ...         return timedeltaextended(seconds=timedelta.total_seconds()) ...      >>> mydurationfield().to_python('00:02:03.456000') timedeltaextended(0, 123, 456000) >>> mydurationfield().to_python('00:02:03.456000') / 2.0 timedeltaextended(0, 61, 728000) 

Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -