Check if Django model field choices exists


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):
  (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?

Asked By: Justin Lucas



First off, models.SmallIntegerField cannot have a max_length option. That are used only in CharField and it’s derivatives. Secondly, according to the documentation, the choices option is mainly used by Django for the Admin site. That said, one option you have is to import the VOTE_TYPE tuple from you file into your file and then checking the value – something like:
VOTE_TYPE = ( (1, "Up"), (-1, "Down"), )
from app.models import VOTE_TYPE
for k,v in VOTE_TYPE:
    if v == new_value:
        return True

Also, if I remember right, you can create a ModelForm from your model and then pass in values to said form which should validate the data against the VOTE_TYPE tuple.

Answered By: Rishabh Manocha
  1. 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

  2. You can easily check if a choice is in list by converting choice list to dict e.g.

    my_choice in dict(VOTE_TYPE)

  3. If possible you can use choiceField or TypedChoiceField , they will validate that the given value exists in the list of choices.

Answered By: Anurag Uniyal

All new projects probably use TextChoices or IntegerChoices.
As it inherits from a builtin enum.Enum, you can now check it in a way your intuition tells you.

from django.db.models import TextChoices

class ExampleChoices(TextChoices):
    example_a = "a"
    example_b = "b", "display_b"
>>> "a" in ExampleChoices
>>> "b" in ExampleChoices
>>> "display_b" in ExampleChoices
Answered By: Tom Wojcik
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.