clowwindy的杂草牧场

   :: 首页 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理
  34 Posts :: 2 Stories :: 74 Comments :: 0 Trackbacks

公告

I'm using django with a legacy mysql db which uses TIMESTAMP columns. Django's inspectdb recognize those fields as int fields. This caused troubles if you want to render its value into a readable date. I googled and found this solution:

http://ianrolfe.livejournal.com/36017.html

代码
from django.db import models
from datetime import datetime
from time import strftime
#
#
Custom field types in here.
#
class UnixTimestampField(models.DateTimeField):
"""UnixTimestampField: creates a DateTimeField that is represented on the
database as a TIMESTAMP field rather than the usual DATETIME field.
"""
def __init__(self, null=False, blank=False, **kwargs):
super(UnixTimestampField, self).
__init__(**kwargs)
# default for TIMESTAMP is NOT NULL unlike most fields, so we have to
# cheat a little:
self.blank, self.isnull = blank, null
self.null
= True # To prevent the framework from shoving in "not null".

def db_type(self):
typ
=['TIMESTAMP']
# See above!
if self.isnull:
typ
+= ['NULL']
if self.auto_created:
typ
+= ['default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP']
return ' '.join(typ)

def to_python(self, value):
return datetime.from_timestamp(value)

def get_db_prep_value(self, value):
if value==None:
return None
return strftime('%Y%m%d%H%M%S',value.timetuple())

 

It worked, until I started to use lookups on these UnixTimestampField fields(such as __gte, __lte, etc). Django will raise a TypeError if I you do .filter(somefield__lte=datetime.now()).

I made some changes to the original code, and finally the lookups works as well:

 

from datetime import datetime
from time import strftime,mktime
#
#
Custom field types in here.
#
class UnixTimestampField(models.DateTimeField):
"""UnixTimestampField: creates a DateTimeField that is represented on the
database as a TIMESTAMP field rather than the usual DATETIME field.
"""
__metaclass__ = models.SubfieldBase

def __init__(self, null=False, blank=False, **kwargs):
super(UnixTimestampField, self).
__init__(**kwargs)
# default for TIMESTAMP is NOT NULL unlike most fields, so we have to
# cheat a little:
self.blank, self.isnull = blank, null
self.null
= True # To prevent the framework from shoving in "not null".

def db_type(self):
typ
=['TIMESTAMP']
# See above!
if self.isnull:
typ
+= ['NULL']
if self.auto_created:
typ
+= ['default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP']
return ' '.join(typ)

def to_python(self, value):
return datetime.fromtimestamp(value)

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

def get_db_prep_value(self, value):
if value==None:
return None
return value

 

posted on 2010-09-11 18:34 clowwindy 阅读(...) 评论(...) 编辑 收藏