跟踪Django中所有模型的更改

Div*_*gal 4 python django database-versioning django-models

我正在使用Django + DRF Web应用程序工作,我想跟踪数据库中所有模型实例的更改,并保留所做的所有更改的日志,即:

TABLE - Table to which record was added/modified
FIELD - Field that was modified.
PK_RECORD - Primary Key of the model instance that was modified.
OLD_VAL - Old Value of the field.
NEW_VAL - New Value of the field.
CHANGED_ON - Date it was changed on.
CHANGED_BY - Who changed it?
REVISION_ID - Revision ID of the current Model Instance.
Run Code Online (Sandbox Code Playgroud)

稍后,我希望用户能够跟踪对模型所做的更改,并查看实例的哪个版本用于特定操作,以便可以跟踪所有内容。

为此,我尝试了解django中用于跟踪数据库模型更改的各种软件包,其中一些在此处列出:

django-model-audit软件包

我尝试了django-reversiondjango-simple-historydjango-audit-log django-historicalrecords,但是我不明白我应该如何以及为什么使用这些软件包,因为其中有些似乎对要求太高了。因此,经过两天的搜索和阅读有关如何跟踪模型更改的大量帖子,我基本上什么也没做。

我是Django新手,不胜感激。

如果不清楚,请随时评论您的查询。提前致谢 :)

Abi*_* Mg 5

您是否已探究django信号pre_save?https://docs.djangoproject.com/en/dev/topics/signals/

from django.db.models.signals import pre_save          
from django.dispatch import receiver
from myapp.models import MyModel

@receiver(pre_save, sender=MyModel)
def my_handler(sender, instance=None, **kwargs):
    # instance variable will have the record which is about to be saved. 
    # So log your details accordingly.
Run Code Online (Sandbox Code Playgroud)

  • 请注意,批量操作不会触发信号,因此不会记录这些更改。 (5认同)
  • `MyModel.objects.bulk_create(my_model1, my_model2)`。这将创建参数中给出的所有“MyModel”实例。但这将使用单个数据库查询一次性创建它们。此操作不会触发任何信号。函数“bulk_update”的工作原理类似。有关更多详细信息,请参阅 https://docs.djangoproject.com/en/2.2/ref/models/querysets/#bulk-create 。 (2认同)