Comparing 2 model entities
Is there an easy way to compare to entities to to check for property value differences? I want something like this:
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' )
For simplest scenario you can compare objects field by field e.g.
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"))
output:
username differ 'anurag' != 'uniyal'
You can later on improve it if you need to further compare foerign keys etc
and i think you are aware that in your example clone_me
is not actually a clone of me
, it is me
Try using sets:
differences = set(me.__dict__) ^ set(cloned_me.__dict__)
if differences:
self.response.out.write('These 2 objects have different property values')
You could even output the attributes that were different (they're contained in the new differences set).
精彩评论