Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get string from TextChoices class in Django

class Foo(models.Model):
    class Bar(models.TextChoices):
        CODE_A = 'A', "special code A"
        CODE_B = 'B', "not so special code B"

    bar = models.CharField(max_length=1, choices=Bar.choices)

The text choices look like tuples but they aren't:

print(Foo.Bar.CODE_A[1])

Gives "IndexError: string index out of range". I was expecting to get "special code A". How do I access the code string programmatically from a view, not from within a template and not just the code constant?

like image 964
gornvix Avatar asked Oct 30 '25 09:10

gornvix


1 Answers

Use .label -- (Django doc) attribute as

print(Foo.Bar.CODE_A.label)
In [12]: class Bar(models.TextChoices):
    ...:     CODE_A = 'A', "special code A"
    ...:     CODE_B = 'B', "not so special code B"
    ...: 

In [13]: Bar.CODE_A.name
Out[13]: 'CODE_A'

In [14]: Bar.CODE_A.label
Out[14]: 'special code A'
like image 75
JPG Avatar answered Nov 02 '25 07:11

JPG