auto_now和auto_now_add之间的区别 [英] Difference between auto_now and auto_now_add

查看:55
本文介绍了auto_now和auto_now_add之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Django 模型字段中了解的是

What I understood in Django models field's attributes is

  • auto_now -每次调用Model.save()时,将字段的值更新为当前时间和日期.
  • auto_now_add -使用记录创建的时间和日期更新值.
  • auto_now - updates the value of field to current time and date every time the Model.save() is called.
  • auto_now_add - updates the value with the time and date of creation of record.

我的问题是,如果模型中的文件同时包含设置为True的 auto_now auto_now_add ,该怎么办?在这种情况下会发生什么?

My question is what if a filed in model contains both the auto_now and auto_now_add set to True? What happens in that case?

推荐答案

auto_now 优先(显然,因为它每次都会更新字段,而 auto_now_add 仅在创建时更新).这是 DateField.pre_save 方法:

auto_now takes precedence (obviously, because it updates field each time, while auto_now_add updates on creation only). Here is the code for DateField.pre_save method:

def pre_save(self, model_instance, add):
    if self.auto_now or (self.auto_now_add and add):
        value = datetime.date.today()
        setattr(model_instance, self.attname, value)
        return value
    else:
        return super().pre_save(model_instance, add)

如您所见,如果设置了 auto_now 或设置了两个 auto_now_add 且对象是新对象,则该字段将接收当天的日期.

As you can see, if auto_now is set or both auto_now_add is set and the object is new, the field will receive current day.

DateTimeField.pre_save相同 :

def pre_save(self, model_instance, add):
    if self.auto_now or (self.auto_now_add and add):
        value = timezone.now()
        setattr(model_instance, self.attname, value)
        return value
    else:
        return super().pre_save(model_instance, add)

这篇关于auto_now和auto_now_add之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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