Django – Keeping history of a field

Question:

Using django 1.7 admin page, I want to Person objects to have a unique Note while keeping the history of the Note field.
Here is my code:

class Note(models.Model):
    note = models.TextField(blank=True, default='')
    date = models.DateTimeField(auto_now_add=True)

    def __unicode__(self):
        return self.note


class NoteHist(models.Model):
    id = models.AutoField(primary_key=True)
    note = models.ForeignKey('Note')

    def __unicode__(self):
        return str(self.note)


class Person(models.Model):
    name = models.CharField(max_length=20, primary_key=True)
    note = models.ForeignKey('NoteHist')


    def __unicode__(self):
        return self.name

Firstly, when pushing the save button on the Note dialog, the popup window redirects to a blank page as if it’s broken; but I can refresh the main admin page to list the note.
Seondly, the notes are not Person specific. I mean Person2 can select Notes written by Person1.
I just want display the last note written by a specific Person while keeping the history of his notes.
By the way, I do not need to show the history in the admin page if that makes it easier.
Please guide me with this.

Asked By: max

||

Answers:

The basic idea is to create a new instance of NoteHist every time you update the Note object by overriding the “save” method of Note.

Here’s a similar question: Store versioned history of Field in a Django model

Apparantly, there is a package that stores Django model state on every create/update/delete and also supports integration with django admin: https://github.com/treyhunner/django-simple-history

Answered By: Bidhan Bhattarai

This library tracks changes to a model field: https://github.com/grantmcconnaughey/django-field-history

Answered By: creatio-mitchell
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.