The problem that django time field auto_now cannot be edited

By adding auto_now to DateTimeField (time field), the current time can be automatically obtained when data is added and modified, but when it is directly modified, the modification will fail. This is because if auto_now and auto_now_add are specified, the field becomes read-only.

Therefore, we can achieve the same method by defining that the current time is always the default value, and it can also be modified.

step:

1. First introduce the timezone function module at the top of models.py:

from django.db import models
import django.utils.timezone as timezone

2. Configure in the target field:

add_time = models.DateTimeField('添加时间',default=timezone.now)

This allows modification:

#此段代码仅供参考
totalHistory.add_time = Day.objects.get(id=12).time
totalHistory.save()    #修改完别忘了save

Replenish:

1.

auto_now can automatically get the current time when data is added and modified

auto_now_add only automatically gets the time when the data is added

2. When using auto_now, the data is not updated. It may be caused by not using save() on the target after modification through the update method.

Guess you like

Origin blog.csdn.net/qq_58174484/article/details/126181820