本文介绍了Django:将对象用作字典键是否合理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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:Math> ;: [<标准:学生可以执行计算。>]}



这是我昨天询问有关。

解决方案

可变对象不应该真的是用作字典键。也就是说,这是因为基本模型类根据模型的主键定义了 __ hash __ ,这不太可能改变。但我宁愿直接使用pk作为关键。


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.

解决方案

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.

这篇关于Django:将对象用作字典键是否合理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 16:26