Bober
Bober

Reputation: 479

What is the best way to implement persistent data model in Django?

What I need is basically a database model with version control. So that every time a record is modified/deleted, the data isn't lost, and the change can be undone.


I've been trying to implement it myself with something like this:

from django.db import models

class AbstractPersistentModel(models.Model):
    time_created = models.DateTimeField(auto_now_add=True)
    time_changed = models.DateTimeField(null=True, default=None)
    time_deleted = models.DateTimeField(null=True, default=None)

    class Meta:
        abstract = True

Then every model would inherit from AbstractPersistentModel.

Problem is, if I override save() and delete() to make sure they don't actually touch the existing data, I'll still be left with the original object, and not the new version.

After trying to come up with a clean, safe and easy-to-use solution for some hours, I gave up.


Is there some way to implement this functionality that isn't overwhelming?

It seems common enough problem that I thought it would be built into Django itself, or at least there'd be a well documented package for this, but I couldn't find any.

Upvotes: 0

Views: 362

Answers (2)

Netizen29
Netizen29

Reputation: 226

When I hear version control for models and Django, I immediately think of django-reversion.

Then, if you want to access the versions of an instance, and not the actual instance, simply use the Version model.

from reversion.models import Version

versions = Version.objects.get_for_object(instance)

Upvotes: 1

JD Gamboa
JD Gamboa

Reputation: 382

I feel you can work around your issue not by modifying your models but by modifying the logic that access them.

So, you could have two models for your same object: one that can be your staging area, in which you store values as the ones you mention, such as time_created, time_modified, and modifying_user, or others. From there, in the code for your views you go through that table and select the records you want/need according to your design and store in your definitive table.

Upvotes: 0

Related Questions