栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Django中的时间戳字段

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Django中的时间戳字段

关于这一点,实际上有一篇非常好的和翔实的文章。此处:http:
//ianrolfe.livejournal.com/36017.html

该页面上的解决方案已被弃用,因此我进行了以下操作:

from django.db import modelsfrom datetime import datetimefrom time import strftimeclass 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, connection):        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):        if isinstance(value, int): return datetime.fromtimestamp(value)        else: return models.DateTimeField.to_python(self, value)    def get_db_prep_value(self, value, connection, prepared=False):        if value==None: return None        # Use '%Y%m%d%H%M%S' for MySQL < 4.1        return strftime('%Y-%m-%d %H:%M:%S',value.timetuple())

要使用它,您要做的就是:

timestamp = UnixTimestampField(auto_created=True)

在MySQL中,该列应显示为:

'timestamp' timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP onUPDATE CURRENT_TIMESTAMP,

唯一的缺点是它仅适用于MySQL数据库。但是您可以轻松地为其他人修改它。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/661020.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号