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!
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!
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.
This is how I get the difference between the two instances with the help of serializers and deepdiff. Why serializer? as we have to get the whole nested data of the instance for comparison.
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