Log all save/update/delete actions in all django models
Question: There are several models in my django app. Some of them derive from
models.Model, some - from django-hvad's translatable model. I want to log
every save/delete/update operation on them. I am aware of standard django
logger of admin actions, but they are too brief and non-verbose to satisfy my
needs.

Generally speaking, one common way to achieve this is to define super-class
with these operations and extend each model from it. This is not my case
because some of my models are translatable and some are not.

Second way are aspects/decorators. I guess, python/django must have something
like that, but I don't know what exactly :)

Please, provide me with the most suitable way to do this logging. Thanks!


Answer: You could write a mixin for your model.

    
    
    import logging
    
    class LogOnUpdateDeleteMixin(models.Model):
        pass
    
        def delete(self, *args, **kwargs):
            super(LogOnUpdateDeleteMixin, self).delete(*args, **kwargs)
            logging.info("%s instance %s (pk %s) deleted" % (str(self._meta), str(self), str(self.pk),) # or whatever you like
    
        def save(self, *args, **kwargs):
            super(LogOnUpdateDeleteMixin, self).save(*args, **kwargs)
            logging.info("%s instance %s (pk %s) updated" % (str(self._meta), str(self), str(self.pk),) # or whatever you like
    
    class Meta:
        abstract = True
    

Now just use it in your model.

    
    
    class MyModel(LogOnUpdateDeleteMixin, models.Model):
        ...
        # Update/Delete actions will write to log. Re-use your mixin as needed in as many models as needed.
    

You can re-use this mixin again and again. Perform translation as you wish,
set some attributes in your models and check for them in the mixin.

