django中的时间戳字段

KVI*_*ISH 17 python mysql django

我有一个MySQL数据库,现在我正在生成所有的datetime字段models.DateTimeField.有没有办法获得一个timestamp?我希望能够在创建和更新等方面进行自动更新.

关于django的文档没有这个?

KVI*_*ISH 17

实际上有一篇关于此的非常好且内容丰富的文章.这里:http: //ianrolfe.livejournal.com/36017.html

页面上的解决方案略有弃用,因此我执行了以下操作:

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())
Run Code Online (Sandbox Code Playgroud)

要使用它,您所要做的就是: timestamp = UnixTimestampField(auto_created=True)

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

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

  • `get_db_prep_value`函数已过期,因为它仅适用于MySQL <4.1上的`TIMESTAMP`列.对于现代版本的MySQL,使用'%Y-%m-%d%H:%M:%S'而不是'%Y%m%d%H%M%S'. (2认同)