django刚开始用,碰到不少问题,还没来得及看,先记下。原文链接:
http://www.cnblogs.com/clowwindy/archive/2010/09/11/Django_TIMESTAMP_Field.html
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
本文介绍了一种在Django中自定义UnixTimestampField的方法,该字段可在数据库层面使用TIMESTAMP类型,并解决了在进行日期时间查询时遇到的问题。


4万+

被折叠的 条评论
为什么被折叠?



