Django - 记录对模型的更改

时间:2013-10-12 16:44:15

标签: django

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

放在哪里的最佳位置?我试图把它放在模型和模型中形成保存方法,但目前没有任何运气。有人有任何例子吗?

基本上:

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

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

2 个答案:

答案 0 :(得分:0)

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

Here

但如果它是临时的,我更喜欢在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'
        },
    },
}

答案 1 :(得分:0)

这是我的处理方式,到目前为止效果良好:

# 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))

difference变量将为您提供两个实例之间不同的字段列表。我还发现添加不希望检查差异的模型字段很有帮助(例如,我们知道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)