我希望我的所有模型都继承自一个“loggingMixin”类,问题是,没有使用loggingMixin中定义的保存(),而是使用了标准的save()。(loggingmixin中的print语句都没有执行,我的回溯总是引用视图中的object.save(),而不是loggingmixin中出现的错误。
所有其他的日志工作,因为他们应该,我可以保存和删除对象。但没有得到记录。谢谢事先的帮助!
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
下面是一个从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')]
1条答案
按热度按时间busg9geu1#
顺序很重要-〉交换机基本模型和LoggingMixin
请查看https://whiztal.io/mixins-in-django-and-django-rest-framework/