Skip to content

Instantly share code, notes, and snippets.

@marceloleiva
Forked from goutham2027/django_reversion.md
Created July 12, 2016 17:39
Show Gist options
  • Save marceloleiva/9f171f15038117ec30c38a300f6c14e9 to your computer and use it in GitHub Desktop.
Save marceloleiva/9f171f15038117ec30c38a300f6c14e9 to your computer and use it in GitHub Desktop.
using django reversion
pip install django-reversion

Add reversion to INSTALLED_APPS

INSTALLED_APPS = [
...
...
...
'reversion',
]

Add 'reversion.middleware.RevisionMiddleware' to MIDDLEWARE_CLASSES

MIDDLEWARE_CLASSES = [
...
...
...
'reversion.middleware.RevisionMiddleware',
]

Do migrations.

python manage.py migrate

After migration two tables are created reversion_revision, reversion_version

Registering models to reversion

# models.py
from reversion import revisions as reversion
class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def __str__(self):
        return self.question_text
    
    def get_versions(self):
        return reversion.get_for_object(self)

    def was_published_recently(self):
        now = timezone.now()
        return now - datetime.timedelta(days=1) <= self.pub_date <= now

    was_published_recently.admin_order_field = 'pub_date'
    was_published_recently.boolean = True
    was_published_recently.short_description = 'Published recently?'

        #return self.pub_date >= timezone.now() - datetime.timedelta(days=1) #buggy_code

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

    def __str__(self):
        return self.choice_text
    
    def get_versions(self):
        return reversion.get_for_object(self)
        
reversion.register(Question)
reversion.register(Choice)

Add some questions, choices from Admin interface.

In django shell

q = Question.objects.last()

from reversion import revisions as reversion
revisions = reversion.get_for_object(q)

## to get user who made the change
revisions.first().revision.user

## created date
revisions.first().revision.date_created

## object fields
revisions.first().field_dict

## to get model instance
revisions.first().object_version.object
revisions.first().object_version.object.question_text
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment