Python Django:访问给定字段的选择元组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18706098/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 11:32:08  来源:igfitidea点击:

Django: Access given field's choices tuple

pythondjangodjango-modelsviews

提问by Furbeenator

I would like to get the named values of a choices field for a choice that is not currently selected. Is this possible?

我想获取当前未选择的选项的选项字段的命名值。这可能吗?

For instance: models.py

例如:models.py

FILE_STATUS_CHOICES = (
    ('P', 'Pending'),
    ('A', 'Approved'),
    ('R', 'Rejected'),
)

class File(models.Model):
    status = models.CharField(max_length=1, default='P', choices=FILE_STATUS_CHOICES)

views.py

视图.py

f = File()
f.status = 'P'
f.save()

old_value = f.status

print f.get_status_display()
> Pending

f.status = 'A'
f.save()

new_value = f.status

print f.get_status_display()
> Approved

How can I get the old display value from the 'P' to 'Pending?' I may be able to do so by creating a form in the view and accessing its dictionary of values/labels. Is this the best/only approach?

如何从“P”到“Pending”获取旧的显示值?我可以通过在视图中创建一个表单并访问它的值/标签字典来做到这一点。这是最好/唯一的方法吗?

采纳答案by alecxe

This is pretty much ok to import your choice mapping FILE_STATUS_CHOICESfrom models and use it to get Pendingby P:

这是非常确定导入你的选择映射FILE_STATUS_CHOICES从模型,并用它来获得PendingP

from my_app.models import FILE_STATUS_CHOICES

print dict(FILE_STATUS_CHOICES).get('P')

get_FIELD_display()method on your model is doing essentially the same thing:

get_FIELD_display()模型上的方法基本上做同样的事情:

def _get_FIELD_display(self, field):
    value = getattr(self, field.attname)
    return force_text(dict(field.flatchoices).get(value, value), strings_only=True) 

And, since there is a flatchoicesfield on the model field, you can use it with the help of _metaand get_field_by_name()method:

并且,由于flatchoices模型字段上有一个字段,您可以在_metaget_field_by_name()方法的帮助下使用它:

choices = f._meta.get_field_by_name('name')[0].flatchoices
print dict(choices).get('P')

where fis your model instance.

f你的模型实例在哪里。

Also see:

另见:

回答by Ibrohim Ermatov

I recommend using Choicefrom django-model-utils: https://django-model-utils.readthedocs.io/en/latest/utilities.html#choices.

我建议使用Choice来自django-model-utilshttps://django-model-utils.readthedocs.io/en/latest/utilities.html#choices

I use it in every my models if I need choice field. See examples, it has excellent options.

如果我需要选择字段,我会在我的每个模型中使用它。查看示例,它有很好的选择。