Django datetime问题(default = datetime.now()) [英] Django datetime issues (default=datetime.now())

查看:670
本文介绍了Django datetime问题(default = datetime.now())的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的数据库模型:

  from datetime import datetime 

class TermPayment(models。模型):
#切出一些字段,与问题无关
date = models.DateTimeField(default = datetime.now(),blank = True)

添加新实例时:

  tp = TermPayment.objects.create(** kwargs)

我有一个问题:数据库在日期字段中具有相同的值 - 第一次付款的日期。服务器重新启动后 - 一个记录有新日期,其他记录与第一个记录相同。看起来像一些数据缓存被使用,但我找不到在哪里。



数据库:mysql 5.1.25



django v1.1.1

解决方案

它看起来像 datetime.now()正在评估,而不是每次添加记录时。



Django有一个功能可以完成您要做的工作: / p>

  date = models.DateTimeField(auto_now_add = True,blank = True)
pre>

  date = models.DateTimeField(default = datetime 。现在,空白=真)

第二个例子与您目前所拥有的不同之处在于缺乏的括号。通过传递没有括号的 datetime.now ,您将传递实际的函数,每次添加一个记录时都会调用该函数。如果你传递它 datetime.now(),那么你只是评估函数并传递返回值。



更多信息,请参见Django的模型字段参考


I have such db model:

from datetime import datetime    

class TermPayment(models.Model):
    # cut out some fields, non relevant to the question
    date = models.DateTimeField(default=datetime.now(), blank=True)

And when new instance is added:

tp = TermPayment.objects.create(**kwargs)

I've an issue: all records in database have the same value in date field - the date of the first payment. After server restart - one record have new date and others have the same as the first. It's look like some data cache is used but I can't find where.

database: mysql 5.1.25

django v1.1.1

解决方案

it looks like datetime.now() is being evaluated when the model is defined, and not each time you add a record.

Django has a feature to accomplish what you are trying to do already:

date = models.DateTimeField(auto_now_add=True, blank=True)

or

date = models.DateTimeField(default=datetime.now, blank=True)

The difference between the second example and what you currently have is the lack of parentheses. By passing datetime.now without the parentheses, you are passing the actual function, which will be called each time a record is added. If you pass it datetime.now(), then you are just evaluating the function and passing it the return value.

More information is available at Django's model field reference

这篇关于Django datetime问题(default = datetime.now())的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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