db" T"例如,一个具有日期时间字段的表,
CREATE TABLE `exec_job` (
`job_id` int(11) NOT NULL AUTO_INCREMENT,
`status` int(11) NOT NULL,
`create_time` datetime NOT NULL,
`finish_time` datetime NOT NULL,
PRIMARY KEY (`job_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
在一台机器上,例如机器IP是192.168.0.100。
我的Django App" M"是另一台机器,例如机器IP是192.168.0.200, 应用程序M使用db T。
当我将数据保存或更新到db时,我发现" create_time"字段和" finish_time"字段使用192.168.0.200的时间进行保存。 虽然,如何在我的Django应用程序代码中使用db time保存或更新datetime字段的datetime?
模特课这样:
class ExecJob(models.Model):
JobId = models.AutoField(db_column = "job_id", primary_key = True)
Status = models.IntegerField(db_column = "status", default = 0)
CreateTime = models.DateTimeField(db_column = "create_time", auto_now_add = True)
FinishTime = models.DateTimeField(db_column = "finish_time", auto_now = True)
class Meta :
db_table = "exec_job"
这样的应用代码:
jobobj = ExecJob(
#JobId = models.AutoField(db_column = "job_id", primary_key = True)
Status = 0,
#CreateTime = , # be commented
#FinishTime = timezone.now(), # be commented
)
jobobj.save()
答案 0 :(得分:0)
您可以在模型类
中创建以下方法def save(self, *args, **kwargs):
if not self.id:
self.CreateTime = datetime.datetime.now()
self.FinishTime = datetime.datetime.now()
return super(ExecJob, self).save(*args, **kwargs)