29

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?

Jeremy
  • 1
  • 85
  • 340
  • 366
pablete
  • 1,030
  • 1
  • 12
  • 21
  • 3
    Did you try to do so? What did you find? Moreover, *why* do you want them to be, what are you trying to achieve? – Martijn Pieters Nov 14 '12 at 11:54
  • 6
    related/duplicate of http://stackoverflow.com/questions/7042530/django-is-it-reasonable-to-use-objects-as-dictionary-keys – Vajk Hermecz Nov 14 '12 at 11:57
  • I needed the key itself as an object in the same place i needed the value of the dict, it works, surprisingly. Also, as as @VajkHermecz said, it's a duplicate question, more details there. – pablete Nov 14 '12 at 12:41
  • 1
    BTW It might be a better approach to use the primary key of the object as the key in the dictionary... – Vajk Hermecz Nov 14 '12 at 12:43
  • 4
    I don't think this is really a duplicate. The other question says *"I have done so and it works*", whereas this question is asking whether it works at all. The other question is somewhat vague in general; it seems like the OP is just wants confirmation that he's not doing something silly. This is a more precise question, and the title is what I'd search for if I wanted to know. I've edited the question to make it a bit clearer, and am now voting to reopen. – Jeremy Jul 18 '13 at 21:53

1 Answers1

36

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()
Jeremy
  • 1
  • 85
  • 340
  • 366
Pavel Anossov
  • 60,842
  • 14
  • 151
  • 124