Home > Software design >  Create a history record in Django for every UPDATE of a class instance
Create a history record in Django for every UPDATE of a class instance

Time:06-30

I have a model in Django that is used to create an item of stock

class Item(models.Model):
  user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
  description = models.ForeignKey(Item, on_delete=models.CASCADE, related_name='item')
  amount = models.IntegerField(default=0, blank=False)
  place = models.ForeignKey(Place, on_delete=models.CASCADE, related_name='place')
  issue_amount = models.IntegerField(default=0, blank=True)
  receive_amount = models.IntegerField(default=0, blank=True)

The item amount will be updated everytime an item is issued by adding or subtracting the issue or receive amount in a views function that alters the instance amount and calls save on that instance.

I want to be able to keep a record of every update and make this information available to both my frontend and to an admin model.

I found this tutorial in which the poster creates a separate model with the same field values as Item and then writes SQL commands directly to the database to create a TRIGGER that saves each Item field on every update: https://www.youtube.com/watch?v=d26DUXynf8s

Is there a way I can replicate this same behaviour using Django?

CodePudding user response:

You want an audit log library.

There are a few (I've never been completely satisfied with any of them) but I quite like this one.

As you can see in the docs, you register your model for auditing like so...

from django.db import models

from auditlog.registry import auditlog

class MyModel(models.Model):
    pass # Model definition goes here as usual.

auditlog.register(MyModel) # Register the model.

...and then you can access the log for a particular row via the new history property.

log = MyModel.objects.first().history.latest()

You can browse the various other Django audit log options here, and they are all more or less variations on the same theme.

  • Related