简体   繁体   English

在django模型的现场更新

[英]updated at field in django model

I have an updated_at field in a django model that looks like this: 我在django模型中有一个updated_at字段,如下所示:

class Location(models.Model):
    updated_at = models.DateTimeField(auto_now=True, default=timezone.now())

If the model was just created it saves the current time when the model was first created in the updated_at field. 如果刚刚创建了模型,它将保存在updated_at字段中首次创建模型时的当前时间。 I am using this to do something special if the model was updated within the past hour. 如果模型在过去一小时内更新,我正在使用它做一些特别的事情。 Problem is that I only want to do that if the model was updated in the past hour not if the model was created. 问题是,如果模型在过去一小时内更新,我不想这样做,而不是模型是否已创建。 How can I differentiate if the model was updated in the past hour or if the model was created in the past hour? 如何区分模型在过去一小时内是否更新,或者模型是否在过去一小时内创建?

I would just have 2 fields on the model, one for created and one that records updated time like this 我只在模型上有2个字段,一个用于创建,另一个用于记录更新时间

class Location(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

If you are using django-model-utils you can subclass the TimeStampedModel, which has both created and modified fields. 如果您使用的是django-model-utils,则可以继承TimeStampedModel,它具有已创建和已修改的字段。

#Django model utils TimeStampedModel
class TimeStampedModel(models.Model):
    """
    An abstract base class model that provides self-updating
    ``created`` and ``modified`` fields.

    """
    created = AutoCreatedField(_('created'))
    modified = AutoLastModifiedField(_('modified'))

    class Meta:
        abstract = True

class Location(TimeStampedModel):
    """
    Add additional fields
    """

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM