Django自动更改驼峰大小写

问题描述

我正在使用models.IntegerChoices作为Django中的Enum,但是它以更改的方式保存在DB中。

class FruitsEnum(models.IntegerChoices):
    Apple = 1
    RedApple = 2
    GreenApple = 3
    LongBanana = 4
    DragonFruit = 5

但是它像这样保存在数据库中:[['0','Apple'),('1','Redapple'),('2','Greenapple')...]

如您所见,“苹果”一词在两个单词的组合中不是大写的。我该如何实现: [('0','Apple'),('1','Red Apple '),('2','Green Apple ')...]

解决方法

与其传递整数,不如传递一个由整数和相关名称组成的元组。像这样:

class FruitsEnum(models.IntegerChoices):
    Apple = 1,'Apple'
    RedApple = 2,'RedApple'
    GreenApple = 3,'GreenApple'
    LongBanana = 4,'LongBanana'
    DragonFruit = 5,'DragonFruit'

或者,在模型中的IntegerField中,您可以使用类似的元组替换FruitsEnum.choices

[(1,'Apple'),(2,'RedApple'),(3,'GreenApple'),(4,'LongBanana'),(5,'DragonFruit')]

注意:您在此处观察到的任何差异都是纯修饰性的,并且在Django外部(即数据库中)不存在。您可以直接打开数据库,然后看到表中仅存储整数。