[英]Django - get auto_now field in pre_save signal
I'm using Django 2.1.5. 我正在使用Django 2.1.5。
There is a model with 'auto_now' field: 有一个带有“ auto_now”字段的模型:
class BaseModel(models.Model):
id = models.UUIDField(default=uuid.uuid4, editable=False, db_index=True, unique=True, primary_key=True)
updated_at = models.DateTimeField(db_index=True, auto_now=True)
updated_by = models.CharField(max_length=200)
responded_at = models.DateTimeField(db_index=True, null=True, blank=True)
responded_by = models.CharField(max_length=200, null=True, blank=True)
Now, I have a pre_save
signal for that model, and I want to update there the responded_at
and responded_by
fields to be equal to updated_at
and updated_by
. 现在,我有一个pre_save
该模型信号,我想更新那里的responded_at
和responded_by
领域等于updated_at
和updated_by
。 In that signal - the updated_by
value is already the new one, as supposed to be in the end of the request, but the updated_at
is not. 在该信号中, updated_by
值已经是新值,应该在请求的末尾,但是updated_at
不是。 It's the old (current) value. 这是旧的(当前)值。 I want, if possible, to be able to get the value that supposed to be in updated_at
field after the save. 我希望,如果可能的话,能够在保存后得到应该在updated_at
字段中的updated_at
。
The reason I'm using pre_save
signal and not post_save
is because I'm updating the instance inside it. 我使用的原因pre_save
信号,而不是post_save
是因为我更新里面的实例。
Since your are using auto_now
with your updated_at
field, it will inherit editable=False
and blank=True
. 由于您使用的是auto_now
你updated_at
领域,它将继承editable=False
和blank=True
。
As currently implemented, setting auto_now or auto_now_add to True will cause the field to have editable=False and blank=True set. 按照当前的实现,将auto_now或auto_now_add设置为True将导致该字段设置为editable = False和blank = True。
To avoid this, you can write a custom field like this: 为了避免这种情况,您可以编写一个自定义字段,如下所示:
from django.utils import timezone
class AutoDateTimeField(models.DateTimeField):
def pre_save(self, model_instance, add):
return timezone.now()
You can use this in your BaseModel
like this: 您可以在BaseModel
像这样使用它:
class BaseModel(models.Model):
updated_at = models.AutoDateTimeField(default=timezone.now)
# ...
This way the updated_at
field should be editable and your signal should work. 这样, updated_at
字段应该是可编辑的,并且您的信号应该可以工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.