Django get auto\u now字段在pre\u save标志中

2024-09-25 10:34:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我用的是Django 2.1.5。你知道吗

有一个带有“auto\u 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,是因为我正在更新其中的实例。你知道吗


Tags: 模型trueautodbindexby信号models
1条回答
网友
1楼 · 发布于 2024-09-25 10:34:25

因为您的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字段应该是可编辑的,您的信号应该可以工作。你知道吗

相关问题 更多 >