Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
149 views
in Technique[技术] by (71.8m points)

python - Store versioned history of Field in a Django model

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()

The expected behavior is as follows:

  • 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

How should i do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Got it myself.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...