Get the integer value of IntegerChoices given a string in Django?

Viewed 359

Suppose I have

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

in Django 3.2.

Then AType.choices can be used as a dict, e.g. AType.choices[0] or AType.choices[AType.ZERO] is 'Zero'.

What's the easiest way to map from the string to the int (0, 1, 2), e.g., map 'Zero' to 0?

I could make another dict by iterating over each key, value pair, and use the other dict. However, I wonder if there's a more convenient way.

This is somewhat related to this question (other way), or this question (doesn't have the answer), or this question (also doesn't have the answer).

EDIT: Here is my current solution, which is just hand-coded.

    @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
1 Answers

Here is my current solution, which is just hand-coded.

    @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
Related