nameisxi
nameisxi

Reputation: 163

How to get currently selected choice from CharField in Django?

I'm trying to get the currently selected choice from the CharField and use it in str method like this:

class Foo(models.Model):
    measurement_value = models.FloatField(max_length=200)

    CHOICES = (('a', 'Alpha'), ('b', 'Beta'))
    choice = models.CharField(max_length=5, choices=CHOICES, default='a')

    def __str__(self):
        """String representation for the foo object."""
        return str(self.measurement_value) + " " + self.choice   

So for example, if I'd like to add object foo with measurement 10.5 and choice 'a' (Alpha), str would return this: "10.5 Alpha"

Currently, the code that I provided returns this: "10.5 a".

Upvotes: 2

Views: 736

Answers (1)

iklinac
iklinac

Reputation: 15738

You can get the human readable choice name by using instance method get_{}_display

your example

 def __str__(self):
     return str(self.measurement_value) + " " + self.get_choices_display()

Upvotes: 2

Related Questions