Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Django Model instances Hashable?

Tags:

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?

like image 592
pablete Avatar asked Nov 14 '12 11:11

pablete


1 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() 
like image 196
Pavel Anossov Avatar answered Oct 22 '22 17:10

Pavel Anossov