Issue
I have django 3.2 and an IntegerChoices class
class Type(models.IntegerChoices):
GENERAL = 2, _("general address")
DELIVERY = 4, _("delivery address")
BILLING = 6, _("billing address")
I can get the Value name and label easily by doing Type.GENERAL , Type.GENERAL.name and Type.GENERAL.label.
But how can I get these values if I only have the value, e.g. I want to get the Name DELIVERY from the value 4.
Type[4].name ist not working as the list values does not correspond to the int values of the enum.
Thanks Matt
Solution
IntegerChoices.choices
returns you a list of tuples with all content. In your case you'll have something like:
[(2, 'general address'), (4, 'delivery address'), (6, 'billing address')]
Thus it can be done this way:
class Type(models.IntegerChoices):
GENERAL = 2, _("general address")
DELIVERY = 4, _("delivery address")
BILLING = 6, _("billing address")
def label_by_type_value(value):
choices = [c[1] for c in Type.choices if c[0] == value]
return choices[0] if len(choices) else None
Answered By - Yevgeniy Kosmak
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.