Reputation: 1177
Are Django Model instances Hashable? For example, can I use a Django Model instance as a dictionary key, or create a Set of unique models?
If they are Hashable, what causes two Django Model instances to be considered the same? Does it implement Hashable naively such that it only consider them to be the same if they are the same Python object in memory, or does it use the value of the Model instance in some way?
Upvotes: 31
Views: 4980
Reputation: 62908
Model instances are Hashable. They are considered to be the same if they are Models of the same type and have the same primary key. You can see this defined in django.db.models.base
:
class Model(object):
...
def __hash__(self):
return hash(self._get_pk_val())
...
def __eq__(self, other):
return isinstance(other, self.__class__) and \
self._get_pk_val() == other._get_pk_val()
Upvotes: 38