时间戳字段在django [英] Timestamp fields in django

查看:672
本文介绍了时间戳字段在django的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个MySQL数据库,现在我正在生成所有的datetime字段为 models.DateTimeField 。有没有办法获得时间戳?我想要能够在创建和更新等上自动更新。



django上的文档没有这个?

解决方案

这实际上是一个非常好的和翔实的文章。这里:
http://ianrolfe.livejournal.com/36017.html



页面上的解决方案略有不赞成,所以我做了以下工作:

  from django。 db导入模型
from datetime import datetime
from time import strftime

class UnixTimestampField(models.DateTimeField):
UnixTimestampField:创建一个表示的DateTimeField在
数据库中作为TIMESTAMP字段而不是通常的DATETIME字段

def __init __(self,null = False,blank = False,** kwargs):
super(UnixTimestampField,self).__ init __(** kwargs)
#默认为TIMESTAMP不是大多数字段不同,所以我们必须
#作弊一点:$ b​​ $ b self.blank, self.isnull = blank,null
self.null = True#阻止框架在not null中移动。

def db_type(self,connection):
typ = ['TIMESTAMP']
#见上图!
如果self.isnull:
typ + = ['NULL']
如果self.auto_created:
typ + = ['CURRENT_TIMESTAMP更新时CURRENT_TIMESTAMP']
返回''.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):
如果value == None:
return None
#对MySQL使用'%Y%m%d%H%M%S' 4.1
return strftime('%Y-%m-%d%H:%M:%S',value.timetuple())

要使用它,您只需要执行以下操作:
timestamp = UnixTimestampField(auto_created = True) p>

在MySQL中,列应显示为:
'timestamp'timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,



这样做的缺点只在于MySQL数据库。但您可以轻松地修改其他人。


I have a MySQL database, right now I'm generating all of the datetime fields as models.DateTimeField. Is there a way to get a timestamp instead? I want to be able to autoupdate on create and update etc.

The documentation on django doesn't have this?

解决方案

There was actually a very good and informative article on this. Here: http://ianrolfe.livejournal.com/36017.html

The solution on the page is slightly deprecated, so I did the following:

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

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, 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())

To use it, all you have to do is: timestamp = UnixTimestampField(auto_created=True)

In MySQL, the column should appear as: 'timestamp' timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,

Only drawback with this is that it only works on MySQL databases. But you can easily modify it for others.

这篇关于时间戳字段在django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆