Issue
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 ?
Solution
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()
Answered By - willeM_ Van Onsem
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.