从 Django 中的 TextChoices 类获取字符串

gor*_*vix 3 django python-3.x

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)
Run Code Online (Sandbox Code Playgroud)

文本选择看起来像元组,但事实并非如此:

print(Foo.Bar.CODE_A[1])
Run Code Online (Sandbox Code Playgroud)

给出“IndexError:字符串索引超出范围”。我本来期待得到“特殊代码A”。如何以编程方式从视图访问代码字符串,而不是从模板内访问,而不仅仅是代码常量?

JPG*_*JPG 8

使用.label-- (Django doc)属性作为

print(Foo.Bar.CODE_A.label)
Run Code Online (Sandbox Code Playgroud)
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'
Run Code Online (Sandbox Code Playgroud)