Reputation: 1644
I have a django class like this:
class my_thing(models.Model):
AVAILABLE = 1
NOT_AVAILABLE = 2
STATUSES = (
(AVAILABLE, "Available"),
(NOT_AVAILABLE, "Not available")
)
status = models.IntegerField(...., choices = STATUSES)
In another bit of code I have the number corresponding to a status, but due to some legacy code I need to compare it via strings (and I don't want to hard code it anywhere other than the model definition - DRY)
So in the code I have the number "1" and I want to get the text "Available".
My current (awful) workaround is to do the following:
status_getter = my_thing()
my_thing.status = my_thing.AVAILABLE
comparison_str = status_getter.get_status_display()
Is there a better/builtin way to directly access the string value for the field's choices given that I don't have an object of that type already instantiated? I could write a function
def get_status_on_value(self, value):
for tup in STATUSES:
if tup[0] == value:
return tup[1]
But I have a sneaking suspicion django has a built-in way to do this
Upvotes: 1
Views: 84
Reputation: 599876
Not really. Your best bet is to convert the CHOICES tuple to a dict and do a lookup:
status_dict = dict(my_thing.STATUSES)
return status_dict[value]
Upvotes: 3