查找同一模型的两个实例之间哪些字段不同 [英] Find which fields are different between two instances of the same Model
问题描述
好吧,我想这个问题可以自己解释。
Well, I think the question explains itself.
我有两个Django模型实例,我想知道哪些字段不同。
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?
干杯!
推荐答案
让我们说 obj1
和 obj2
是2 MyModel
的模型实例。
Lets says obj1
and obj2
are 2 instances of the model MyModel
.
要知道在Django模型的两个实例上哪些字段不同,我们首先得到模型的所有字段并将其存储在变量 my_model_fields
中。
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
然后我们将 filter()
与 lambda
即可知道它们之间的字段不同。
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()
函数将返回两个实例之间不同的模型字段的列表。
The filter()
function will return me the list of model fields which differ between the two instances.
这篇关于查找同一模型的两个实例之间哪些字段不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!