简体   繁体   English

Django Model Mixin:使用 Mixins 添加记录器到 model save() 和 delete()

[英]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.我希望我所有的模型都继承自一个“loggingMixin”class。问题是,不是使用 LoggingMixin 中定义的 save(),而是使用标准的 save()。 (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. (loggingmixin 中的任何打印语句都没有执行,我的回溯总是从我的视图中引用 object.save() 而不是 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:下面是一个 model 继承自 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订单事项 -> 切换 Basemodel 和 LoggingMixin

class ExistingCalculationsForUrl(LoggingMixin, Basemodel):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM