28

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?

5
  • 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, 2012 at 11:54
  • 6
    related/duplicate of stackoverflow.com/questions/7042530/… Nov 14, 2012 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, 2012 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... Nov 14, 2012 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, 2013 at 21:53

1 Answer 1

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()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.