有没有一种简单的方法来比较两个实体来检查属性值差异?我想要这样的东西:
me = User.get_by_id( 28 )
cloned_me = me
cloned_me.first_name = 'Tom'
if me != cloned_me:
self.response.out.write( 'These 2 objects have different property values' )
答案 0 :(得分:0)
对于最简单的场景,您可以逐字段比较对象,例如
from django.contrib.auth.models import User
def compare(user1, user2):
for field in user1._meta.fields:
val1 = getattr(user1, field.name)
val2 = getattr(user2, field.name)
if val1 != val2:
print "%s differ '%s' != '%s'"%(field.name, val1, val2)
break
compare(User(username="anurag"), User(username="uniyal"))
输出:
username differ 'anurag' != 'uniyal'
如果您需要进一步比较foerign键等,可以稍后进行改进
我认为您知道在您的示例中clone_me
实际上并不是me
的克隆,而是me
答案 1 :(得分:0)
尝试使用套装:
differences = set(me.__dict__) ^ set(cloned_me.__dict__)
if differences:
self.response.out.write('These 2 objects have different property values')
您甚至可以输出不同的属性(它们包含在新的差异集中)。