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?
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With