Issue
Lets say I defined a model class
from model_utils import Choices
class SomeModel(TimeStampedModel):
food_choices = Choices(
(1, "WATER", "Water"),
(2, "BURGER", "Burger"),
(3, "BIRYANI", "Biryani")
)
food = models.IntegerField(choices=food_choices, default=food_choices.WATER)
How do I get the display part while using the choices as a variable?
eg. SomeModel.food_choices.WATER gives me 1, how do I get the value/string "Water"?
I know if I create an instance, then I can fetch the display value using .get_food_display()
for that instance, but I don’t want that I just want to use it directly from the constant created for Choices
, ie food_choices
.
Solution
Got it after some tinkering.
In the Choices
variable, we have tuples where the respective first value is the key, eg. 1,2,3.
food_choices = Choices(
(1, "WATER", "Water"),
(2, "BURGER", "Burger"),
(3, "SALAD", "Salad")
)
We know SomeModel.food_choices.WATER
gives 1
, ie the key.
Now to get 'Water'
directly from the declared Choices
constant we can get it using the declared key for that tuple:
eg.
SomeModel.food_choices[2] # returns 'Burger'
SomeModel.food_choices[0] # throws KeyError: 0
If we don’t want to figure out what index(or magic numbers) 0 or 2 is, then use:
SomeModel.food_choices[SomeModel.food_choices.WATER] # returns 'Water'
Answered By - faruk13
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.