Find which fields are different between two instances of the same Model
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.