我有一个带有文本字段的模型,需要进行版本控制。
class Book(models.Model):
title = models.CharField(max_length=100)
summary = models.TextField()
预期的行为如下:
summary
进行版本控制,而不是整个模型 我该怎么做?
答案 0 :(得分:7)
自己动手。
首先创建一个名为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()
现在,每次更新图书时,都会创建特定图书摘要的新增量版本,除非它没有更改。