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

2024/10/15 9:16:07

Is it reasonable to use objects as keys to a dictionary in django? I have done so and it works. But I am wondering if this is best practice, or if it is going to make difficulties I don't foresee right now.

I am working on a project which deals with educational standards. I have dictionaries with a structure along the lines of {Subject:[Standards]}. The model for subject looks something like:

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

Is it okay to use the objects from this model as keys to my dictionaries, or should I be using a string represenation, such as Subject.subject instead?

If so, does the unicode method affect this? When I tried using Subject.subject as the 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 followup to a question I asked yesterday about using None as a dictionary key.

Answer

Mutable objects shouldn't really be used as dictionary keys. That said, this works because the base model class defines __hash__ in terms of the model's primary key, which is unlikely to change. But I would prefer to use the pk directly as the key.

https://en.xdnf.cn/q/69303.html

Related Q&A

How do I now (since June 2022) send an email via Gmail using a Python script?

I had a Python script which did this. I had to enable something in the Gmail account. For maybe 3 years the script then ran like this: import smtplib, ssl ... subject = some subject message body = &quo…

Fast relational database for simple use with Python [closed]

Closed. This question is seeking recommendations for books, tools, software libraries, and more. It does not meet Stack Overflow guidelines. It is not currently accepting answers.We don’t allow questi…

Event handling with Jython Swing

Im making a GUI by using Swing from Jython. Event handling seems to be particularly elegant from Jython, just setJButton("Push me", actionPerformed = nameOfFunctionToCall)However, trying same…

How Does Deque Work in Python

I am having trouble understanding how the deque works in the snippet of code below, while trying to recreate a queue and a stack in Python.Stack Example - Understoodstack = ["a", "b"…

When to use generator functions and when to use loops in Python

I am coming from a Matlab background and I am finding it difficult to get around the concept of generators in Python. Can someone please answer me the following:The difference between a generator funct…

Airflow - Disable heartbeat logs

My logs are getting completely flooded with useless messages for every heartbeat. [2019-11-27 21:32:47,890] {{logging_mixin.py:112}} INFO - [2019-11-27 21:32:47,889] {local_task_job.py:124} WARNING - T…

different validation in drf serializer per request method

Lets say i have a model like so:class MyModel(models.Model):first_field = models.CharField()second_field = models.CharField()and an API view like so:class MyModelDetailAPI(GenericAPIView):serializer_cl…

How to import r-packages in Python

Im a bit troubled with a simple thing. I was trying to install a package called hunspell, but I discovered it is originally an R package. I installed this version: https://anaconda.org/conda-forge/r-hu…

XPath predicate with sub-paths with lxml?

Im trying to understand and XPath that was sent to me for use with ACORD XML forms (common format in insurance). The XPath they sent me is (truncated for brevity):./PersApplicationInfo/InsuredOrPrinci…

Best way to access and close a postgres database using python dataset

import dataset from sqlalchemy.pool import NullPooldb = dataset.connect(path_database, engine_kwargs={poolclass: NullPool})table_f1 = db[name_table] # Do operations on table_f1db.commit() db.execut…