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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With