鉴于以下模型:
class Title(models.Model):
name = models.CharField(max_length=120)
imdb_id = models.CharField(max_length=20)
created = models.DateTimeField()
last_updated = models.DateTimeField()
如何实现自定义保存方法来更新这两个字段?类似的东西:
def save(self, *args, **kwargs):
now = timezone.now()
# update the created date
if not self.pk:
self.created = now
# update the last modified
previous_obj = Title.objects.get(pk=self.pk) # a way to do this without a second query?
if (previous_obj.name != self.name) or (previous_obj.imdb_id != self.imdb_id):
self.last_updated = now
super(Title, self).save(*args, **kwargs)