从任意值获取 Django 字段 "choice"

Get django field "choice" from arbitrary value

我有一个像这样的 django class:

class my_thing(models.Model):
    AVAILABLE = 1
    NOT_AVAILABLE = 2

    STATUSES = (
                (AVAILABLE, "Available"),
                (NOT_AVAILABLE, "Not available")
                )
    status = models.IntegerField(...., choices = STATUSES)

在另一段代码中,我有对应于状态的数字,但由于一些遗留代码,我需要通过字符串比较它(而且我不想在模型定义以外的任何地方对其进行硬编码 -干)

所以在代码中我有数字“1”,我想获取文本 "Available"。

我当前(糟糕的)解决方法是执行以下操作:

status_getter = my_thing()
my_thing.status = my_thing.AVAILABLE
comparison_str = status_getter.get_status_display()

鉴于我还没有实例化该类型的对象,是否有 better/builtin 方法可以直接访问字段选项的字符串值?我可以写一个函数

def get_status_on_value(self, value):
    for tup in STATUSES:
       if tup[0] == value:
         return tup[1]

但我偷偷怀疑 django 有一个内置的方法来做到这一点

不是真的。最好的办法是将 CHOICES 元组转换为字典并进行查找:

status_dict = dict(my_thing.STATUSES)
return status_dict[value]