[英]Django DateTimeField and datetime.datetime.now() giving different times
我有一个模型,我希望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
。
我怎样才能让这两个日期时间相同?
我已经链接了一个答案将帮助您了解正在发生的事情。 不过,实现您想要的非常简单。
模型.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)
这是 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/")
顺便说一句,你看过这个文档了吗( upload_to
也接受一个可调用的)? 您真的需要表中的name
列吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.