Display field choice as part of model string name

13,371

Use get_gender_display():

return u"%s [%s]" % (self.name, self.get_gender_display())

Note, if you're not using Python 3+ you should be defining __unicode__ rather than __str__.

Share:
13,371

Related videos on Youtube

Ed.
Author by

Ed.

Updated on June 04, 2022

Comments

  • Ed.
    Ed. almost 2 years

    From the django documentation, what if I had

    GENDER_CHOICES = (
        ('M', 'Male'),
        ('F', 'Female'),
    )
    
    class Person(models.Model):
        name = models.CharField(max_length=20)
        gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
    
        def __str__(self):
                return "%s [%s]" % (self.name, self.gender)
    

    What if I wanted the __str definition to display as the full name (Male or Female) for self.gender instead of M or F?

  • Ed.
    Ed. about 12 years
    can you explain the difference between unicode and str? And should I define them both?
  • jfunez
    jfunez about 11 years
    and in a template, you can use: {{ variable.get_fieldname_display }} HTH
  • Torsten Engelbrecht
    Torsten Engelbrecht over 7 years
    In Python 3 you should be defining __str__ rather than __unicode__ though.