在 Django 模型中存储 Field 的版本历史 [英] Store versioned history of Field in a Django model
本文介绍了在 Django 模型中存储 Field 的版本历史的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带有文本字段的模型,需要对其进行版本控制.
I have a model with a text field, that needs to be versioned.
class Book(models.Model):
title = models.CharField(max_length=100)
summary = models.TextField()
预期行为如下:
- 如果我创建一本带有摘要的新书,文本将正常保存
- 如果更新了摘要,则需要将旧状态与版本号和时间戳一起存储在某处
- 应该可以轻松查询当前、一系列或特定版本
- 只有字段
summary
应该被版本化,而不是整个模型
- If i create a new book with a summary, the text will be saved normally
- If the summary is updated, the old state needs to be stored somewhere with a version number and timestamp
- It should be easily possible to query for the current, a range of or specific versions
- Only the field
summary
should be versioned, not the whole model
我该怎么做?
推荐答案
自己搞定.
首先创建一个名为SummaryHistory
的新模型:
First create a new model called 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)
现在扩展初始模型如下:
Now extend the initial model as follows:
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()
现在,每次更新一本书时,都会为该特定书创建一个新的增量版本的摘要,除非它没有更改.
Now, every time you update a book, a new incremented version of the summary for the specific book will be created unless it has not changed.
这篇关于在 Django 模型中存储 Field 的版本历史的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文