自定义保存方法以更新last_modified日期

时间:2014-10-30 19:30:52

标签: python django

鉴于以下模型:

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)

0 个答案:

没有答案