Custom model field for mysql time type.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import datetime

from django.db import models
from django.db.backends.mysql.base import django_conversions
from django.conf import settings
from MySQLdb.constants import FIELD_TYPE

django_conversions.update({FIELD_TYPE.TIME: None})

SECONDS_PER_MIN = 60
SECONDS_PER_HOUR = SECONDS_PER_MIN * 60
SECONDS_PER_DAY = SECONDS_PER_HOUR * 24

class TimeAsTimeDeltaField(models.Field):
    """
    Custom field for mapping TIME columns to timedelta values, not times,
    so that we can store values greater than 24 hours.
    See ticket #354 and http://docs.djangoproject.com/en/1.0/howto/custom-model-fields/#howto-custom-model-fields
    """
    __metaclass__ = models.SubfieldBase
    
    def db_type(self):
        return 'time'
    
    def to_python(self, value):
        if value is None:
            return None
        
        if isinstance(value, datetime.timedelta):
            return value
        
        hours, minutes, seconds = map(int, value.split(':'))
        total_seconds = seconds + (60 * (minutes + (60 * hours)))
        result = datetime.timedelta(seconds=total_seconds)
        return result
    
    def get_db_prep_value(self, value):
        if not value:
            return None
        
        total_seconds = value.seconds + (value.days * SECONDS_PER_DAY)
        return '%02i:%02i:%02i' % (
            total_seconds / SECONDS_PER_HOUR, # hours
            total_seconds / SECONDS_PER_MIN - total_seconds / SECONDS_PER_HOUR * 60, # minutes - Total seconds subtract the used hours
            total_seconds % SECONDS_PER_MIN # seconds
        )

More like this

  1. SelectTimeWidget by bradmontgomery 5 years, 5 months ago
  2. SplitSelectDateTimeWidget by bradmontgomery 5 years, 5 months ago
  3. Querying datetime aware objects in your local timezone by jayliew 1 year, 10 months ago
  4. ModelForm Class saving m2m by ckarrie2 2 years, 6 months ago
  5. Modifying the fields of a third/existing model class by marinho 3 years, 3 months ago

Comments

(Forgotten your password?)