开发者

Use Django Model class inheritance to create an audit log for a table

开发者 https://www.devze.com 2023-01-28 23:49 出处:网络
I want to use http://docs.djangoproject.com/en/dev/topics/db/models/#model-inheritance to subclass an existing model for the purpose of creating a complete history of every change ever made to any rec

I want to use http://docs.djangoproject.com/en/dev/topics/db/models/#model-inheritance to subclass an existing model for the purpose of creating a complete history of every change ever made to any record in the original table.

class Foo:
  data = models.TextField()
  created_at = models.DateTimeField(auto_now_add=True)
  updated_at = models.DateTimeField(auto_now=True)

  def save():
    super(...)
    audit = FooAuditLog.createFromFoo(self)

class FooAuditLog(Foo):
  history_for = models.ForeignKey(Foo)

  def createFromFoo(foo):
    ... #Create the auditlog entry from the original record.

So every time I create or update a record of type "Foo", I want to take a snapshot of the Foo record and add another entry into FooAuditLog. My goal is to have a complete revision history for every Foo record so that I can track each and every change made to each record over time.

What are the pitfalls of this approach? If there are ForeignKey relationships to and out of Foo, do I hav开发者_JAVA百科e to worry about cascade deletes/updates between Foo and FooAuditLog?


Why not use something made such as the Audit Trail app? I can't really see how inheritance really fits into the abstraction needed for logging. Audit Trail uses a simple declaration in the class which packages all of the activities.


Two possible pre-coded solutions are https://github.com/etianen/django-reversion and http://code.djangoproject.com/wiki/AuditTrail . More options are at https://www.djangopackages.com/grids/g/model-audit/

As you note, foreign key references are tricky, especially for Many-To-Many models. You have to decide if the old models are a constraint on new tables, else break those relationships which complicates "undo" considerably.

0

精彩评论

暂无评论...
验证码 换一张
取 消