djang中的时间戳字段

2024-04-16 13:19:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个MySQL数据库,现在我将所有的datetime字段生成为models.DateTimeField。有没有办法改成timestamp?我想能够自动更新的创建和更新等

关于django的文档没有这个?


Tags: django文档数据库datetimemodelsmysqltimestamp办法
3条回答

实际上有一篇关于这方面的很好的信息性文章。在这里: 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())

要使用它,您只需: timestamp = UnixTimestampField(auto_created=True)

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

这样做的唯一缺点是它只在MySQL数据库上工作。但是你可以很容易地为别人修改它。

pip包django unixdatetimefield提供了一个unixdatetimefield字段,您可以直接使用它(https://pypi.python.org/pypi/django-unixdatetimefield/)。

示例模型:

from django_unixdatetimefield import UnixDateTimeField

class MyModel(models.Model):
    created_at = UnixDateTimeField()

Python ORM查询:

>>> m = MyModel()
>>> m.created_at = datetime.datetime(2015, 2, 21, 19, 38, 32, 209148)
>>> m.save()

数据库:

sqlite> select created_at from mymodel;
1426967129

如果有兴趣的话,这是源代码-https://github.com/Niklas9/django-unixdatetimefield

免责声明:我是这个pip包的作者。

要在插入和更新时自动更新,请使用以下命令:

created = DateTimeField(auto_now_add=True, editable=False, null=False, blank=False)
last_modified = DateTimeField(auto_now=True, editable=False, null=False, blank=False)

DateTimeField应该存储UTC(检查您的数据库设置,我从Postgres知道就是这样)。您可以通过以下方式在模板和格式中使用l10n

{{ object.created|date:'SHORT_DATETIME_FORMAT' }}

Unix纪元后的秒数:

{{ object.created|date:'U' }}

https://docs.djangoproject.com/en/1.10/ref/templates/builtins/#date

相关问题 更多 >