Creating a custom Django DateTimeField model

In my last post I ran into a problem. A legacy database stores values as BigInt in MySQL using Unix time. Django uses datetime. I want the nice validation and widgets from Django’s DateTimeField. Here’s how to solve in.

Create a new field, I called it UnixTimestampField and overrode models.DateTimeField.

from django.db import models
from datetime import datetime
from time import strftime, mktime
import time

class UnixTimestampField(models.DateTimeField):
__metaclass__ = models.SubfieldBase

def __init__(self, null=False, blank=False, **kwargs):
super(UnixTimestampField, self).__init__(**kwargs)

def db_type(self):
typ=['bigint']
if self.isnull:
typ += ['NULL']
return ' '.join(typ)

def to_python(self, value):
super(UnixTimestampField, self)
try:
return datetime.fromtimestamp(float(value))
except:
return value

def get_db_prep_value(self, value):
if value==None:
return None
return time.mktime(value.timetuple())

def get_prep_value(self, value):
if value==None:
return None
return time.mktime(value.timetuple())

It seems to work. I’ll update though if I run into any trouble down the line or re-factor it. This is my first attempt at making a custom Django Model Field.

1 thought on “Creating a custom Django DateTimeField model”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s