Previous version of a django-reversion controlled object

2k views Asked by At

I'm using what the django-reversion documents call the low-level API in order to access the reversion history in my own code, apart from the admin. To store metadata, I've extended the Revision model by setting up my own model including a OneToOneField(Revision). So far, so good.

But given that reference to a Revision, how can I access the revision directly before it? For example, to generate a list of changes between this revision and the previous one, is there any more efficient method than calling back to reversion.get_for_object and searching the list for the version I'm looking for?

2

There are 2 answers

2
ejucovy On BEST ANSWER

The Revision object has a date_created attribute, so you could write a query to select the single most recent revision for your object prior to the given revision's date_created. I'd basically copy the implementation of the low-level API's get_for_date function, with one change -- use "date_created__lt" instead of "__lte":

def get_previous(object, date):
    """Returns the latest version of an object prior to the given date."""
    versions = reversion.get_for_object(object)
    versions = versions.filter(revision__date_created__lt=date)
    try:
        version = versions[0]
    except IndexError:
        raise Version.DoesNotExist
    else:
        return version
1
chrisvans On

Version objects have a revision attribute, which has two methods, 'get_next_by_date_created', and 'get_previous_by_date_created', which you could use to traverse version history either way.

version.revision.get_previous_by_date_created()