2

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' )
zakdances
  • 22,285
  • 32
  • 102
  • 173
  • `cloned_me` isn't a copy here - it's simply another reference to the same object. This check will always return `True`. – Nick Johnson Sep 09 '11 at 00:50
  • possible duplicate of [Elegant way to avoid .put() on unchanged entities](http://stackoverflow.com/questions/7330974/elegant-way-to-avoid-put-on-unchanged-entities) – Nick Johnson Sep 09 '11 at 00:52

2 Answers2

0

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

Anurag Uniyal
  • 85,954
  • 40
  • 175
  • 219
0

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).

Jordan Bouvier
  • 308
  • 2
  • 7
  • Is this an efficient method of comparing? From my understanding, bitwise comparisons are expensive. – zakdances Sep 08 '11 at 17:06
  • I'm not sure how expensive it is. The time difference between this and anything possibly faster is probably negligible unless you have a very large data set. – Jordan Bouvier Sep 08 '11 at 19:12