Difference between auto_now and auto_now_add

核能气质少年 提交于 2021-01-20 23:41:09

问题


What I understood in Django models field's attributes is

  • 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.

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?


回答1:


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)

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.

The same for 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)



回答2:


According to the django documentation using but auto_now and auto_now_add as True will result in an error because they are both mutually exclusive.




回答3:


As Official Django documentation says -

auto_now, auto_now_add and default are mutually exclusive and will result in an error if used together



来源:https://stackoverflow.com/questions/51389042/difference-between-auto-now-and-auto-now-add

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!