我正在将应用程序从 Codeigniter 移植到 Django。我想在 Django 中尝试并重新创建的功能之一是能够记录对模型字段值的任何更改。
放在哪里最好?我试图把它放在模型和表单保存方法中,但目前没有任何运气。有没有人去任何例子?
基本上:
if orig.emp_name != self.emp_name: ##在更改表中使用旧值、新值和更改日期/时间创建记录
是否可以遍历所有 ModelForm 字段以检查值的变化?我可以为每个字段键入以上内容,但如果它可以在循环中会更好。
我正在将应用程序从 Codeigniter 移植到 Django。我想在 Django 中尝试并重新创建的功能之一是能够记录对模型字段值的任何更改。
放在哪里最好?我试图把它放在模型和表单保存方法中,但目前没有任何运气。有没有人去任何例子?
基本上:
if orig.emp_name != self.emp_name: ##在更改表中使用旧值、新值和更改日期/时间创建记录
是否可以遍历所有 ModelForm 字段以检查值的变化?我可以为每个字段键入以上内容,但如果它可以在循环中会更好。
这是我处理这个问题的方法,到目前为止效果很好:
# 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))
差异变量将为您提供两个实例之间不同的字段列表。我还发现添加我不想检查差异的模型字段很有帮助(例如,我们知道 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)
使用信号原则: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'
},
},
}