【问题标题】:Django DateTimeField and datetime.datetime.now() giving different timesDjango DateTimeField 和 datetime.datetime.now() 给出不同的时间
【发布时间】:2020-03-26 08:05:45
【问题描述】:

我有一个模型,我希望 name 字段是时间戳的字符串表示形式,另一个字段是实际时间戳。这是我的模型代码:

from django.db import models
from datetime import datetime

class Image(models.Model):
    name = models.CharField(max_length=255, default=datetime.now().strftime("%Y%m%d-%H%M%S"))
    create_date = models.DateTimeField(auto_now_add=True)
    image = models.ImageField(upload_to="images/")

然后我进入 django shell 并输入:

>>> import models
>>> models.Image(image='images/rock.png').save()

这可行,但唯一的问题是两次不对齐。例如,我得到name = 20191201-143119 和create_date = 2019-12-01 14:32:11.445474。

我怎样才能让这两个日期时间相同?

【问题讨论】:

  • 嗨,@dwvldg。这个answer 可能会对你有所帮助

标签: python django


【解决方案1】:

这是 Django 世界中一个很常见的问题。 @eliakin-costa 提到的帖子讨论了这个问题,虽然他的解决方案有效,但我不建议重写 save 方法来获得这种行为,因为它更容易创建一个函数(保持解耦和显式):

from django.db import models
from django.utils import timezone

def default_image_name():
   return timezone.now().strftime("%Y%m%d-%H%M%S")

class Image(models.Model):
    name = models.CharField(max_length=255, default=default_image_name)
    create_date = models.DateTimeField(auto_now_add=True)
    image = models.ImageField(upload_to="images/")

顺便说一句,你看过这个docs(upload_to 也接受可调用)吗?您真的需要在表中添加name 列吗?

【讨论】:

  • 很好的答案,@gmacro.:)
【解决方案2】:

我已链接answer 将帮助您了解正在发生的事情。不过,实现您想要的非常简单。

models.py

from django.db import models
from datetime import datetime

class Image(models.Model):
    name = models.CharField(max_length=255)
    create_date = models.DateTimeField(auto_now_add=True)
    image = models.ImageField(upload_to="images/")

    def save(self, *args, **kwargs):
        if not self.name: 
            self.name = datetime.now().strftime("%Y%m%d-%H%M%S")
        super(Image, self).save(*args, **kwargs) 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-02
    • 2014-12-03
    • 2013-08-17
    • 2018-12-16
    • 2015-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多