How to print / access Django IntegerChoice human readable labels with Model definition

Viewed 108

For the Django Model inherited from IntegerChoices with following human readable strings :

class SomeModel(models.Model):
    class Answer(models.IntegerChoices):
        NO = 0, _('No')
        YES = 1, _('Yes')
        
        __empty__ = _('(Unknown)')


    answer = models.IntegerField(choices=Answer.choices)

    SomeModel.objects.create(answer=0)
    somemodel = SomeModel.objects.filter(answer=0)

    print("Answer : {0}", **somemodel.answer.label** )

How can I access the human-readable 'No' and 'Yes' text via using somemodel.answer.xxx ?

1 Answers

If the name of the field in the model is foo, then you can access this with the .get_foo_display() method [Django-doc].

So if the model looks like:

class SomeModel(models.Model):
    class Answer(models.IntegerChoices):
        NO = 0, _('No')
        YES = 1, _('Yes')
        
        __empty__ = _('(Unknown)')


    answer = models.IntegerField(choices=Answer.choices)

Then you can access the human readable form of a MyModel object somemodel with:

somemodel.get_answer_display()
Related