Django: overridden __hash__ not working for objects from database? -


i have problem django model objects have overridden __hash__() complex uniqueness/distinctiveness constraints want enforce when use them. working fine objects have directly instantiated in memory, not ones retrieve database.

like this:

class animal(models.model):     name = model.charfield('name', max_length=10)      def__hash__(self):         return len(self.name) # silly example purposes of illustration 

and this:

>> = models.animal(name='cat') >> b = models.animal(name='dog') >> len(set((a,b)) > 1 >> a.save() >> b.save() >> len(set(models.animal.objects.all())) > 2 

hmm. whatever hash function being used here, ain't mine. guess it's related lazy fetching / objects not yet in instantiated state, how round it?

this because have implemented __hash__ without implementing __eq__. implement __eq__ , should go.

the length of set([a, b]) 1 because django defines default __eq__ function compares primary keys of objects — before saved, both have id of none, a == b true. after saved, both have been assigned different primary keys, a != b true.


Comments

Popular posts from this blog

django - How can I change user group without delete record -

java - Need to add SOAP security token -

java - EclipseLink JPA Object is not a known entity type -