Django: Display Choice Value

后端 未结 3 929
心在旅途
心在旅途 2020-12-02 04:03

models.py:

class Person(models.Model):
    name = models.CharField(max_length=200)
    CATEGORY_CHOICES = (
        (\'M\', \'Male\'),
              


        
相关标签:
3条回答
  • 2020-12-02 04:34

    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.

    In Views

    person = Person.objects.filter(to_be_listed=True)
    context['gender'] = person.get_gender_display()
    

    In Template

    {{ person.get_gender_display }}
    

    Documentation of get_FOO_display()

    0 讨论(0)
  • 2020-12-02 04:39

    Others have pointed out that a get_FOO_display method is what you need. I'm using this:

    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

    0 讨论(0)
  • 2020-12-02 04:51

    It looks like you were on the right track - get_FOO_display() is most certainly what you want:

    In templates, you don't include () in the name of a method. Do the following:

    {{ person.get_gender_display }}
    
    0 讨论(0)
提交回复
热议问题