Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
“获取django字段”;选择“;从任意值_Django_Python 3.4 - Fatal编程技术网

“获取django字段”;选择“;从任意值

“获取django字段”;选择“;从任意值,django,python-3.4,Django,Python 3.4,我的django课程是这样的: class my_thing(models.Model): AVAILABLE = 1 NOT_AVAILABLE = 2 STATUSES = ( (AVAILABLE, "Available"), (NOT_AVAILABLE, "Not available") ) status = models.IntegerField(....

我的django课程是这样的:

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

    STATUSES = (
                (AVAILABLE, "Available"),
                (NOT_AVAILABLE, "Not available")
                )
    status = models.IntegerField(...., choices = STATUSES)
在另一段代码中,我有对应于状态的数字,但由于一些遗留代码,我需要通过字符串进行比较(除了模型定义-DRY之外,我不想在任何地方硬编码)

所以在代码中我有数字“1”,我想得到文本“可用”

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

status_getter = my_thing()
my_thing.status = my_thing.AVAILABLE
comparison_str = status_getter.get_status_display()
如果我没有实例化该类型的对象,是否有更好的/内置的方法直接访问字段选择的字符串值?我可以写一个函数

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

但我暗自怀疑django有一种内在的方法来做到这一点。最好将选项元组转换为dict并进行查找:

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

绝对是一个比我可怕的黑客更好的解决方案。