Using Django Model Class Inheritance to Create an Audit Log for a Table

I want to use http://docs.djangoproject.com/en/dev/topics/db/models/#model-inheritance to subclass an existing model in order to create a complete history of all changes ever made to any record in the source 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 an entry like "Foo", I want to take a snapshot of the Foo entry and add another entry to the FooAuditLog. My goal is to have a complete change history for each Foo record so that I can track every change made to each record over time.

What are the pitfalls of this approach? If there is a ForeignKey relationship with and from Foo, do I need to worry about cascading deletions / updates between Foo and FooAuditLog?

+3
source share

Source: https://habr.com/ru/post/1778874/


All Articles