我正在将应用程序从 Codeigniter 移植到 Django。我想在 Django 中尝试和重新创建的功能之一是能够记录对模型字段值的任何更改。
最好把它放在哪里?我尝试将其放入模型和表单保存方法中,但目前没有任何运气。有人举过例子吗?
基本上:
如果 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)
关于Django - 记录对模型的更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19336675/