在django模型中使用默认日期的正确方法 [英] Correct way to use a default date in a django model

查看:1314
本文介绍了在django模型中使用默认日期的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个模型,它们都有一个默认为当前日期的日期字段,无论如何。今天有人指出,他们正在从其中一个人那里得到一个错误,这个错误是将日期设置为12月19日而不是12月23日(今天在写作时)。



认为这两个领域都是相同的,所以我检查了两者之间的意想不到的差异,找到了一个。但是我很惊讶,因为工作是一个像我这样的错误。字段设置如下:

 #工作字段
date_stamp = models.DateField(default = datetime.date .today)

#断字段
date_statp = models.DateField(default = datetime.date.today())

我一直认为需要调用函数函数以确保该值未被缓存。实际上是相反的吗?有人可以解释这两个实例在实例创建上的实际解释吗?

解决方案

第一个字段:

  date_stamp = models.DateField(default = datetime.date.today)

将回调作为默认值。这意味着每次需要填充默认值时,都将调用该函数。



另一个:

  date_statp = models.DateField(default = datetime.date.today())

执行函数 datetime.date.today ,返回当时日期的值。所以当Django初始化模型时,它将在那个确切的时刻将默认值设置为日期。将使用此默认值,直到Django再次重新初始化模型,通常仅在启动时。


I have two models, both of which have a date field defaulting to the current date, whatever that may be. Today someone pointed out they were getting an error from one of them, which was setting dates to 19 December instead of 23 December (today at the time of writing).

I had thought both fields were set up identically so I checked for an unintended difference between the two and found one. But I was surprised because the 'working' one was the one that looked to me like it contained an error. The fields are set up like this:

# Working field
date_stamp = models.DateField(default=datetime.date.today)

# Broken field
date_statp = models.DateField(default=datetime.date.today())

I always thought the today function needed to be called to ensure the value wasn't cached. Is the reverse in fact true? Can someone explain how these two are actually interpreted on model instance creation?

解决方案

The first field:

date_stamp = models.DateField(default=datetime.date.today)

takes a callback as a default value. That means that the function will be called everytime the default value needs to be filled.

The other one:

date_statp = models.DateField(default=datetime.date.today())

executes the function datetime.date.today, which returns the value of the date at that moment. So when Django initializes the models, it will set the default value to the date at that precise moment. This default value will be used untill Django reinitializes the models again, which is usually only at startup.

这篇关于在django模型中使用默认日期的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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