Issue
please help out. I have the class that inherits from models.IntegerChoices, however, I know getting the value can be retried for instance if i want to retrieve the value for Daily, I can run RecurringType.DAILY, and I can get the value using RecurringType.DAILY.value and label by RecurringType.DAILY.label. But now, what if I have the value and want to get the label, how can I do that, I have tried so many things on here but nothing seems to work.
Below is the code
from django.db import models
class RecurringType(models.IntegerChoices):
DAILY = 1, ("Daily")
WEEKLY = 2, ("Weekly")
MONTHLY = 3, ("Monthly")
Solution
You can achieve this in the following ways.
print(RecurringType(1).label)
# 'Daily'
print(RecurringType(10).label)
# ValueError: 10 is not a valid RecurringType
But the above way should used be used if you're certain that the value you're passing in is valid, or it will raise a ValueError
. So if you go this way, try to catch this error just in case the value passed is invalid.
Another way is adding a method to RecurringType
.
from django.db import models
class RecurringType(models.IntegerChoices):
DAILY = 1, ("Daily")
WEEKLY = 2, ("Weekly")
MONTHLY = 3, ("Monthly")
@classmethod
def get_label_with_value(cls, value):
for choice in cls.choices:
if choice[0] == value:
return choice[1]
return None
print(RecurringType.get_label_with_value(1))
# 'Daily'
print(RecurringType.get_label_with_value(10))
# returns None and won't raise a ValueError
Answered By - Temi
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.