5

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
dfrankow
  • 20,191
  • 41
  • 152
  • 214

2 Answers2

0

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
dfrankow
  • 20,191
  • 41
  • 152
  • 214
0

You can create a mapping and then do simple dict access by key:

label_mapping = {label: value for value, label in AType.choices}
# outputs: { 'Zero': 0, 'One': 1, 'Two': 2 }

@classmethod
def string_to_int(cls, the_string):
    """Convert the string value to an int value, or return None."""
    return label_mapping.get(the_string)
Stefan_EOX
  • 1,279
  • 1
  • 16
  • 35