在 Django 中获取给定字符串的 IntegerChoices 的整数值?

dfr*_*kow 5 django django-models

假设我有

class AType(models.IntegerChoices):
    ZERO = 0, 'Zero'
    ONE = 1, 'One'
    TWO = 2, 'Two'
Run Code Online (Sandbox Code Playgroud)

在 Django 3.2 中。

然后AType.choices可以用作字典,例如AType.choices[0]orAType.choices[AType.ZERO]是“零”。

从字符串映射到 int (0, 1, 2) 的最简单方法是什么,例如将“零”映射到 0?

我可以通过迭代每个键、值对来创建另一个字典,并使用另一个字典。不过我想知道是否有更方便的方法。

这与这个问题(其他方式),或者这个问题(没有答案),或者这个问题(也没有答案)有些相关。

编辑:这是我当前的解决方案,它只是手工编码的。

    @classmethod
    def string_to_int(cls, the_string):
        """Convert the string value to an int value, or return None."""
        for num, string in cls.choices:
            if string == the_string:
                return num
        return None
Run Code Online (Sandbox Code Playgroud)

dfr*_*kow 0

这是我当前的解决方案,它只是手工编码。

    @classmethod
    def string_to_int(cls, the_string):
        """Convert the string value to an int value, or return None."""
        for num, string in cls.choices:
            if string == the_string:
                return num
        return None
Run Code Online (Sandbox Code Playgroud)