Are Django Model instances Hashable?
Asked Answered
T

1

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?

Tumefacient answered 14/11, 2012 at 11:53 Comment(5)
Did you try to do so? What did you find? Moreover, why do you want them to be, what are you trying to achieve?Underground
related/duplicate of #7043030Naked
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.Tumefacient
BTW It might be a better approach to use the primary key of the object as the key in the dictionary...Naked
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.Frieder
M
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()
Monochord answered 14/11, 2012 at 15:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.