Python Django:显示选择值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4320679/
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
Django: Display Choice Value
提问by Shankze
models.py:
模型.py:
class Person(models.Model):
name = models.CharField(max_length=200)
CATEGORY_CHOICES = (
('M', 'Male'),
('F', 'Female'),
)
gender = models.CharField(max_length=200, choices=CATEGORY_CHOICES)
to_be_listed = models.BooleanField(default=True)
description = models.CharField(max_length=20000, blank=True)
views.py:
视图.py:
def index(request):
latest_person_list2 = Person.objects.filter(to_be_listed=True)
return object_list(request, template_name='polls/schol.html',
queryset=latest_person_list, paginate_by=5)
On the template, when I call person.gender, I get 'M'or 'F'instead of 'Male'or 'Female'.
在模板上,当我调用 时person.gender,我得到'M'or'F'代替'Male'or 'Female'。
How to display the value ('Male'or 'Female') instead of the code ('M'/'F')?
如何显示值('Male'或'Female')而不是代码('M'/ 'F')?
回答by jMyles
It looks like you were on the right track - get_FOO_display()is most certainly what you want:
看起来您走在正确的轨道上 -get_FOO_display()这肯定是您想要的:
In templates, you don't include ()in the name of a method. Do the following:
在templates 中,您不包括()在方法的名称中。请执行下列操作:
{{ person.get_gender_display }}
回答by Muhammad Faizan Fareed
For every field that has choices set, the object will have a get_FOO_display() method, where FOO is the name of the field. This method returns the “human-readable” value of the field.
对于每个设置了选项的字段,对象都有一个 get_FOO_display() 方法,其中 FOO 是字段的名称。此方法返回字段的“人类可读”值。
In Views
在视图中
person = Person.objects.filter(to_be_listed=True)
context['gender'] = person.get_gender_display()
In Template
在模板中
{{ person.get_gender_display }}
回答by Daniel O'Brien
Others have pointed out that a get_FOO_display method is what you need. I'm using this:
其他人指出 get_FOO_display 方法正是您所需要的。我正在使用这个:
def get_type(self):
return [i[1] for i in Item._meta.get_field('type').choices if i[0] == self.type][0]
which iterates over all of the choices that a particular item has until it finds the one that matches the items type
它迭代特定项目的所有选择,直到找到与项目类型匹配的选择

