我自己搞定了。
首先创建一个名为的新模型SummaryHistory
:
class SummaryHistory(models.Model):
version = models.IntegerField(editable=False)
book = models.ForeignKey('Book')
text = models.TextField()
class Meta:
unique_together = ('version', 'book',)
def save(self, *args, **kwargs):
# start with version 1 and increment it for each book
current_version = SummaryHistory.objects.filter(book=self.book).order_by('-version')[:1]
self.version = current_version[0].version + 1 if current_version else 1
super(SummaryHistory, self).save(*args, **kwargs)
现在扩展初始模型如下:
class Book(models.Model):
title = models.CharField(max_length=100)
summary = models.TextField()
def summary_history(self):
return SummaryHistory.objects.filter(book=self).order_by('-version')
def save(self, *args, **kwargs):
super(Book, self).save(*args, **kwargs)
# save summary history
summary_history = self.summary_history()
if not summary_history or self.summary != summary_history[0].text:
newSummary = SummaryHistory(book=self, text=self.summary)
newSummary.save()
现在,每次更新书籍时,都会为特定书籍创建一个新的递增版本的摘要,除非它没有更改。