Django 日期时间问题(默认值=datetime.now()) [英] Django datetime issues (default=datetime.now())

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

问题描述

我有以下数据库模型:

from datetime import datetime    

class TermPayment(models.Model):
    # I have excluded fields that are irrelevant to the question
    date = models.DateTimeField(default=datetime.now(), blank=True)

我使用以下方法添加了一个新实例:

I add a new instance by using the below:

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

我的问题:数据库中的所有记录在日期字段中都有相同的值,即第一次付款的日期.服务器重新启动后,一条记录具有新的日期,其他记录与第一条记录相同.看起来好像缓存了一些数据,但我找不到在哪里.

My issue: all records in database have the same value in date field, which is the date of the first payment. After the server restarts, one record has the new date and the other records have the same as the first. It looks as if some data is cached, but I can't find where.

数据库:mysql 5.1.25

database: mysql 5.1.25

django v1.1.1

django v1.1.1

推荐答案

看起来 datetime.now() 在定义模型时正在评估,而不是每次添加记录时.

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

Django 有一个功能可以完成您已经尝试做的事情:

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

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

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

第二个示例与您当前拥有的示例之间的区别在于缺少括号.通过传递不带括号的 datetime.now,您将传递实际的函数,每次添加记录时都会调用该函数.如果你传递它datetime.now(),那么你只是在评估函数并将返回值传递给它.

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.

更多信息可在 Django 的模型字段参考

More information is available at Django's model field reference

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

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