You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django迁移choices到utils.py后触发TypeError: 'CharField'不可迭代

Django模型choices迁移后字段报错问题解决

问题场景

原本运行正常的Media模型,将嵌套元组类型的choices迁移到同应用下的utils.py后,其他字段均可正常使用该choices,但second_umbrella字段触发TypeError: 'CharField' object is not iterable错误。仅修改umbrella字段的choices时程序正常,一旦修改second_umbrella就报错,重命名字段并生成新迁移文件也无法解决。

问题根源

在models.py中,你定义了变量umbrella=UMBRELLA(),但随后模型里的第一个字段也命名为umbrella。Python解析代码时,当处理到第二个字段second_umbrella时,变量umbrella已经被覆盖成了models.CharField对象,而非原本的choices元组,导致Django尝试迭代CharField对象时触发错误。

解决方案

方案1:修改变量名避免冲突

将models.py中存储choices的变量名改为与字段名不重复的名称,比如UMBRELLA_CHOICES:

修正后的models.py

from database.utils import UMBRELLA
# 改名避免和字段名冲突
UMBRELLA_CHOICES = UMBRELLA()

class Media(models.Model):
    umbrella = models.CharField(max_length=20, choices=UMBRELLA_CHOICES, default='Undefined', null=True, blank=True)
    second_umbrella = models.CharField(max_length=20, choices=UMBRELLA_CHOICES, default='Undefined', null=True, blank=True)

方案2:将utils中的choices改为常量(更推荐)

既然你的choices是固定值,不需要动态生成,直接在utils.py中定义为常量而非函数,这样使用更简洁:

修正后的utils.py

# Umbrella 直接定义为常量元组
UMBRELLA = (
    ("DH", "DH"),
    ("SE", "SE"),
    ("PA", "PA"),
    ("PF", "PF")
)

修正后的models.py

from database.utils import UMBRELLA

class Media(models.Model):
    umbrella = models.CharField(max_length=20, choices=UMBRELLA, default='Undefined', null=True, blank=True)
    second_umbrella = models.CharField(max_length=20, choices=UMBRELLA, default='Undefined', null=True, blank=True)

验证

修改完成后,运行python manage.py check验证是否还有错误,再重新启动服务或生成迁移文件即可正常使用。

内容的提问来源于stack exchange,提问作者Rivered

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 23:50:25