Django: Is it possible to use objects as dictionary keys?

Is it possible to use objects as keys to a dictionary in django? I did it and it works. But I wonder if this is the best practice, or if it will be difficult, I do not foresee right now.

I am working on a project that addresses educational standards. I have dictionaries with a structure along the lines {Subject:[Standards]} . The model for the object looks something like this:

 class Subject(models.Model): subject = models.CharField(max_length=255, unique=True) def __unicode__(self): return self.subject 

Is it possible to use objects from this model as keys to my dictionaries, or should I use a string representation like Subject.subject?

If so, does the unicode method affect it? When I tried to use Subject.subject as a key, I got things like {u'Math': [<Subject: Students can perform calculations.>]} Using objects as keys, it looks like {<Subject: Math>: [<Standard: Students can perform calculations.>]}

This is a question for the question that I asked yesterday about using None as a dictionary key .

+4
source share
4 answers

Variable objects should not be used as dictionary keys. However, this works because the base class of the model defines __hash__ in terms of the primary key of the model, which is unlikely to change. But I would prefer to use pk directly as a key.

+7
source

It depends on how you want to use them. I would suggest a simpler approach:

The dictionary keys may be the Primary Model Key.

+2
source

Assuming that objects implement a good hash function, I would say that there is nothing wrong with using objects as keys, but this is just my personal opinion.

-1
source

It is better to use a string representation, because when you need to search, you will need to write out all this, which will hurt, and if in the future you want to change the Unicode representation, you will have to find a way to rewrite the old Unicode to look up.

Good luck.

-1
source

All Articles