我尝试将其作为模型的选择变量来实现:
>>> choices = (
... (1, 'Primary'), (2, 'Secondary'), (3, 'Tertiary')
... )
但它失败了这个准神秘的错误:
characters.CharacterArcanumLink.priority: (fields.E005) 'choices' must
be an iterable containing (actual value, human readable name) tuples.
让我们看看,
看起来不错。
深入研究code,看起来对Django 1.7进行了新的检查:
def _check_choices(self):
if self.choices:
if (isinstance(self.choices, six.string_types) or
not is_iterable(self.choices)):
return [
checks.Error(
"'choices' must be an iterable (e.g., a list or tuple).",
hint=None,
obj=self,
id='fields.E004',
)
]
elif any(isinstance(choice, six.string_types) or
not is_iterable(choice) or len(choice) != 2
for choice in self.choices):
return [
checks.Error(
("'choices' must be an iterable containing "
"(actual value, human readable name) tuples."),
hint=None,
obj=self,
id='fields.E005',
)
]
else:
return []
else:
return []
这是第二次检查,在看起来很腥的elif之后。让我在上面isinstance
元组上尝试choices
:
>>> any(isinstance(choice, six.string_types) for choice in choices)
False
不好!如何进行一些修改?
>>> any(isinstance(choice[1], six.string_types) for choice in choices)
True
>>>
优异。
我的问题是,我错过了什么吗?我sure这曾经是可能的。为什么不再可能?我错误地执行了这个吗?
我还在code.djangoproject上打开了ticket,如果有帮助吗?
触发它的代码分为两部分:
class Trait(models.Model):
PRIORITY_CHOICES = (
(None, '')
)
MIN = 0
MAX = 5
current_value = IntegerRangeField(min_value=MIN, max_value=MAX)
maximum_value = IntegerRangeField(min_value=MIN, max_value=MAX)
priority = models.PositiveSmallIntegerField(choices=PRIORITY_CHOICES, default=None)
class Meta:
abstract = True
和
class CharacterSkillLink(CharacterLink, SkillLink, Trait):
PRIORITY_CHOICES = (
(1, 'Primary'), (2, 'Secondary'), (3, 'Tertiary')
)
speciality = models.CharField(max_length=200)
答案 0 :(得分:4)
问题在于你有一个选择 - 外括号不构造元组,只提供分组。元组的创建由逗号提供,而不是括号。
((None, '')) == (None, '')
你应该留下一个尾随逗号来表示你想要一个单项元组(或使用一个列表):
PRIORITY_CHOICES = ((None, ''), )