Are Django Model instances Hashable?

Question:

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?

Asked By: pablete

||

Answers:

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()
Answered By: Pavel Anossov
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.