Django - 记录对模型的更改

use*_*278 6 django

我正在将应用程序从 Codeigniter 移植到 Django。我想在 Django 中尝试和重新创建的功能之一是能够记录对模型字段值的任何更改。

最好把它放在哪里?我试图将它放在模型和表单保存方法中,但目前没有任何运气。有没有人举个例子?

基本上:

if orig.emp_name != self.emp_name: ##使用旧值、新值和更改日期/时间在更改表中创建记录

是否可以遍历所有 ModelForm 字段以检查值的变化?我可以为每个字段输入上述内容,但如果它可以在循环中会更好。

小智 6

这是我处理这个问题的方法,到目前为止效果很好:

# get current model instance to update
instance = MyModel.objects.get(id=id)

# use model_to_dict to convert object to dict (imported from django.forms.models import model_to_dict)
obj_dict = model_to_dict(instance)

# create instance of the model with this old data but do not save it
old_instance = MyModel(**obj_dict)

# update the model instance (there are multiple ways to do this)
MyModel.objects.filter(id=id).update(emp_name='your name') 

# get the updated object
updated_object = MyModel.objects.get(id=id)

# get list of fields in the model class
my_model_fields = [field.name for field in cls._meta.get_fields()]

# get list of fields if they are different
differences = list(filter(lambda field: getattr(updated_object, field, None)!= getattr(old_instance, field, None), my_model_fields))
Run Code Online (Sandbox Code Playgroud)

Differences 变量将为您提供两个实例之间不同的字段列表。我还发现添加我不想检查差异的模型字段很有帮助(例如,我们知道updated_date 总是会更改,因此我们不需要跟踪它)。

skip_diff_fields = ['updated_date']

my_model_fields = []
for field in cls._meta.get_fields():
    if field.name not in skip_diff_fields:
        my_model_fields.append(field.name)
Run Code Online (Sandbox Code Playgroud)


Oli*_*ons 1

使用信号原理:pre_save、post_save、pre_delete、post_delete等。

这里

但如果它是临时的,我更喜欢在 中配置所有查询的日志记录的方式settings.py:将其添加到您的末尾settings.py并根据您的需要进行调整:

LOGGING = {
    'disable_existing_loggers': False,
    'version': 1,
    'handlers': {
        'console': {
            # logging handler that outputs log messages to terminal
            'class': 'logging.StreamHandler',
            'level': 'DEBUG',  # message level to be written to console
        },
    },
    'loggers': {
        '': {
            # this sets root level logger to log debug and higher level
            # logs to console. All other loggers inherit settings from
            # root level logger.
            'handlers': ['console'],
            'level': 'DEBUG',
            'propagate': False, # this tells logger to send logging message
                                # to its parent (will send if set to True)
        },
        'django.db': {
            # django also has database level logging
            'level': 'DEBUG'
        },
    },
}
Run Code Online (Sandbox Code Playgroud)