Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find which fields are different between two instances of the same Model

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!

like image 886
gabn88 Avatar asked Jul 28 '15 16:07

gabn88


1 Answers

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.

like image 110
Rahul Gupta Avatar answered Oct 20 '22 10:10

Rahul Gupta