【发布时间】:2023-03-28 14:56:01
【问题描述】:
我正在尝试使用可调用对象创建具有选择字段的模型,以便 Django 在选择列表更改时不会创建迁移,如this 问题中所述。
class Quote(models.Model):
severity = models.IntegerField(choices=get_severity_choices)
...
class get_severity_choices(object):
def __iter__(self):
for item in SEVERITY_CHOICES:
yield item
在哪里
SEVERITY_CHOICES = (
(1, 'Low'),
(2, 'Medium'),
(3, 'High'),
)
但是,我收到一条错误消息:
quoting.Quote.severity: (fields.E004) 'choices' must be an iterable (e.g., a list or tuple).
【问题讨论】:
-
对于参数选择,唯一可接受的字段是元组,或者有时可以是列表,但在这里你试图传递一个类并回顾参考,尝试将 SEVERITY_CHOICES 的名称更改为 get_severity_choices。
-
我认为您可以将
for item in SEVERITY_CHOICES: yield item替换为return iter(SEVERITY_CHOICES)。甚至severity = models.IntegerField(choices=SEVERITY_CHOICES)