Well, I think the question explains itself.
I have two instances of a Django Model and I would like to know which fields differ.
How could you do this in a smart way?
Cheers!
答案 0 :(得分:5)
Lets says obj1
and obj2
are 2 instances of the model MyModel
.
To know which fields differ on two instances of a Django model, we first get all the fields of a model and store it in a variable my_model_fields
.
my_model_fields = MyModel._meta.get_all_field_names() # gives me the list of all the model fields defined in it
Then we apply filter()
with lambda
to know which fields differ between them.
filter(lambda field: getattr(obj1,field,None)!=getattr(obj2,field,None), my_model_fields)
The filter()
function will return me the list of model fields which differ between the two instances.
答案 1 :(得分:1)
这就是我在序列化器和deepdiff的帮助下获得两个实例之间差异的方式。为什么是序列化器?因为我们必须获取实例的整个嵌套数据进行比较。
from deepdiff import DeepDiff
.
.
.
old_data = modelserilaizer(instance1).data
new_data = modelserilaizer(instance2).data
instance_diff = DeepDiff(old_data, new_data, ignore_order=True)
# output {'values_changed': {"root['item'][3]['rr'][2]['rate']": {'new_value': '0.03', 'old_value': '0.02'}}}
if "values_changed" in instance_diff:
# do you work here