python - Django:使用对象作为字典键是否合理?

标签 python django dictionary key

在django中使用对象作为字典的键是否合理?我已经这样做了并且有效。但我想知道这是否是最佳做法,或者它是否会造成我现在无法预见的困难。

我正在从事一个涉及教育标准的项目。我的字典结构类似于 {Subject:[Standards]} .主题的模型看起来像:

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

  def __unicode__(self):
    return self.subject

是否可以使用此模型中的对象作为我的字典的键,或者我应该使用字符串表示,例如 Subject.subject?

如果是这样,unicode 方法是否对此有影响?当我尝试使用 Subject.subject 作为键时,我得到了类似 {u'Math': [<Subject: Students can perform calculations.>]} 的东西使用对象作为键,看起来像{<Subject: Math>: [<Standard: Students can perform calculations.>]}

这是对我昨天提出的关于 using None as a dictionary key 的问题的跟进.

最佳答案

可变对象不应该真正用作字典键。也就是说,这是可行的,因为基础模型类根据模型的主键定义 __hash__,这不太可能改变。但我更愿意直接使用 pk 作为 key 。

关于python - Django:使用对象作为字典键是否合理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7042530/

相关文章:

python - 独特的排列发生器?

python - 索引多个数组

Python 调用 "self.property"和创建返回 "self.property"的方法有什么区别?

c++ - std::map 比较指针

python - 更新字典

python - 仅使用python置换最后一列

python - 导入错误;在 PyCharm 中使用 Python 3.5 安装 Reportlab 3.4 时出现问题

python /Django : How to render user-submitted videos code fragments as embedded videos?

database - Django 表单我无法保存图片文件

Python 使用字符串作为字典键