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. 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?
如果刚刚创建了模型,它将保存在updated_at字段中首次创建模型时的当前时间。如果模型在过去一小时内更新,我正在使用它做一些特别的事情。问题是,如果模型在过去一小时内更新,我不想这样做,而不是模型是否已创建。如何区分模型在过去一小时内是否更新,或者模型是否在过去一小时内创建?
1 个解决方案
#1
12
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
"""
#1
12
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
"""