Well, I think the question explains itself.
好吧,我认为问题解释了。
I have two instances of a Django Model and I would like to know which fields differ.
我有两个Django模型实例,我想知道哪些字段不同。
How could you do this in a smart way?
你怎么能以聪明的方式做到这一点?
Cheers!
1 个解决方案
#1
5
Lets says obj1
and obj2
are 2 instances of the model MyModel
.
让我们说obj1和obj2是模型MyModel的2个实例。
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
.
要知道哪些字段在Django模型的两个实例上有所不同,我们首先获取模型的所有字段并将其存储在变量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.
然后我们应用带lambda的filter()来知道它们之间的区别。
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.
filter()函数将返回两个实例之间不同的模型字段列表。
#1
5
Lets says obj1
and obj2
are 2 instances of the model MyModel
.
让我们说obj1和obj2是模型MyModel的2个实例。
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
.
要知道哪些字段在Django模型的两个实例上有所不同,我们首先获取模型的所有字段并将其存储在变量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.
然后我们应用带lambda的filter()来知道它们之间的区别。
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.
filter()函数将返回两个实例之间不同的模型字段列表。