clowwindy的杂草牧场

   :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
  34 随笔 :: 1 文章 :: 75 评论 :: 13万 阅读

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   clowwindy  阅读(3267)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
点击右上角即可分享
微信分享提示