gpt4 book ai didi

python - Django - 获取 pre_save 信号中的 auto_now 字段

转载 作者:太空宇宙 更新时间:2023-11-03 20:40:55 26 4
gpt4 key购买 nike

我使用的是 Django 2.1.5。

有一个带有“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)

现在,我有该模型的 pre_save 信号,我想将其中的 responded_atresponded_by 字段更新为等于updated_atupdated_by。在该信号中 - updated_by 值已经是新值,正如应该在请求末尾一样,但 updated_at 不是。这是旧(当前)值。如果可能的话,我希望能够在保存后获取应该在 updated_at 字段中的值。

我使用 pre_save 信号而不是 post_save 的原因是因为我正在更新其中的实例。

最佳答案

由于您将 auto_nowupdated_at 字段一起使用,因此它将继承 editable=Falseblank=True >.

作为docs状态:

As currently implemented, setting auto_now or auto_now_add to True will cause the field to have editable=False and blank=True set.

为了避免这种情况,您可以编写如下自定义字段:

from django.utils import timezone


class AutoDateTimeField(models.DateTimeField):
def pre_save(self, model_instance, add):
return timezone.now()

您可以在 BaseModel 中使用它,如下所示:

class BaseModel(models.Model):
updated_at = models.AutoDateTimeField(default=timezone.now)
# ...

这样,updated_at 字段应该是可编辑的,并且您的信号应该可以工作。

关于python - Django - 获取 pre_save 信号中的 auto_now 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56872720/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com