Django Model Mixin: Adding loggers to model save() and delete() using Mixins

I would like all my models to inherit from a single "loggingMixin" class. The problem is that, instead of using the save() defined in the LoggingMixin, the standard save() is used. (none of the print statements in the loggingmixin are executed and my traceback always referenced the object.save() from my views and not the error raised in the loggingmixin.

all other logs works as they should and i can save and delete objects. but nothing gets logged. thanks in advance for the help!

import logging
logger = logging.getLogger(__name__)

## this file defines a mixin to logg all saves, updates, deletes and errors

class LoggingMixin:
    
    def save(self, *args, **kwargs):
        try:
            print("---------------------------------------------------------------1")
            if hasattr(self.pk):
                print("---------------------------------------------------------------2")
                if self.pk is None:
                    # Object is new
                    print("---------------------------------------------------------------3")
                    super(LoggingMixin, self).save(*args, **kwargs)
                    logger.info(f"{self._meta.db_table} object saved: " + str(str(self).split('\n')[1]))
                else:
                    # Object is being updated
                    print("---------------------------------------------------------------4")
                    super(LoggingMixin, self).save(*args, **kwargs)
                    logger.info(f"{self._meta.db_table} object updated: " + str(str(self).split('\n')[1]))
            else:
                # Object is being updated
                print("---------------------------------------------------------------5")
                super(LoggingMixin, self).save(*args, **kwargs)
                logger.info(f"{self._meta.db_table} object updated: " + str(str(self).split('\n')[1]))
        # error when saving
        except Exception as e:
            print("-------------------------------------------------------------6")
            logger.error(f"Error saving {self._meta.db_table} object: " + str(str(self).split('\n')[1]) + f"Error: {e}")
            raise e

    def delete(self, *args, **kwargs):
        # delete log
        try:
            super(LoggingMixin, self).delete(*args, **kwargs)
            logger.info(f"{self._meta.db_table} object deleted. ID: {str(self.pk)}")
        # error when deleting
        except Exception as e:
            logger.error(f"Error deleting {self._meta.db_table} object: " + str(str(self).split('\n')[1]) + f"Error: {e}")
            raise e

Here is an example of a model inheriting from loggingmixin:

class ExistingCalculationsForUrl(Basemodel, LoggingMixin):
    url = models.CharField(max_length=512)
    content_type = models.ForeignKey(ContentType, on_delete=models.PROTECT, default=None)
    object_id = models.UUIDField(default=uuid.uuid4, editable=False)
    content_object = GenericForeignKey('content_type', 'object_id')
    week = models.ForeignKey('Weeks', on_delete=models.CASCADE, related_name='%(class)s_related_week')
    existing_calculation = models.JSONField()

    class Meta:
        managed = True
        db_table = 'existing_calculations_for_url'
        constraints = [models.UniqueConstraint(fields=['url', 'object_id', 'week'], name='unique_existing_calculation_for_url')]

order matters -> switch Basemodel and LoggingMixin

class ExistingCalculationsForUrl(LoggingMixin, Basemodel):

take a look at https://whiztal.io/mixins-in-django-and-django-rest-framework/

Back to Top