I’m attempting to check if a value exists in the choices tuple set for a model field.
For example lets say I have a Model like this:
class Vote(models.Model):
VOTE_TYPE = (
(1, "Up"),
(-1, "Down"),
)
value = models.SmallIntegerField(max_length=1, choices=VOTE_TYPES)
Now lets say in a view I have a variable new_value = 'Up' that I would like to use as the value field in a new Vote. How can I first check to see if the value of that variable exists in the VOTE_TYPE tuple?
Are you sure you want to set value to “Up”? that is a display value, you might be interested in setting value to -1 or 1
You can easily check if a choice is in list by converting choice list to dict e.g.
my_choice in dict(VOTE_TYPE)If possible you can use choiceField or TypedChoiceField , they will validate that the given value exists in the list of choices.