我使用的是enum34包,如here所述。
以下是文章中使用的示例:
from common.utils import ChoiceEnum
class StudentTypes(ChoiceEnum):
freshman = 0
sophomore = 1
junior = 2
senior = 3
# within your models.Model class...
student_type = models.CharField(max_length=1, choices=StudentTypes.choices())
但是,在我的枚举字段中,我希望使用:
(例如16:9
)。
有办法做到这一点吗?
答案 0 :(得分:0)
你能确定你明白什么是枚举吗?在示例中,新生由0
表示,大二由1
表示,等等。您不能使用字符串(例如"16:9"
)作为枚举中的表示。
枚举中的名称必须是有效的Python标识符。但是,还有其他方法可以将字符串(例如带冒号的字符串)映射到整数,反之亦然。
答案 1 :(得分:0)
我不确定我是否完全理解你的问题。你想在枚举中使用16:9作为属性吗?你不能因为:不是任何属性的正确字符。您不能在任何地方使用代码16:9中的变量。请参阅:https://docs.python.org/3/reference/lexical_analysis.html#grammar-token-identifier
答案 2 :(得分:0)
我已经发现我不需要enum34
包,并且可以手动轻松完成:
WIDE= 0
BOX = 1
RATIO_CHOICES = (
(WIDE, '16:9'),
(BOX, '4:3'),
)
aspect_ratio = models.IntegerField(choices=RATIO_CHOICES, default=WIDE)