anon
anon

Reputation:

How to access a specific element from a CHOICES list in Django?

In my models, I have a choices list, such as:

class Graduation(models.Model):
    YEAR_IN_SCHOOL_CHOICES = [
        ('FR', 'Freshman'),
        ('SO', 'Sophomore'),
        ('JR', 'Junior'),
        ('SR', 'Senior'),
        ('GR', 'Graduate'),
    ]
    student_level = models.CharField(max_length=2, choices=YEAR_IN_SCHOOL_CHOICES)

In my views, I want to get the value for a specific element. I have this:

search = 'JR'
all_choices = Graduation.YEAR_IN_SCHOOL_CHOICES

My goal is to get Junior returned by the system. How can I do that?

I tried:

all_choices[search]

but that doesn't work. I know I can change the format of my choices list in the models, but in this case my models can not be changed. What is the right way to obtain the label from this list? Do I have to loop through the list and use an if statement? That doesn't seem efficient but I am not sure if I have another choice.

Upvotes: 1

Views: 1621

Answers (3)

Thierno Amadou Sow
Thierno Amadou Sow

Reputation: 2573

try this i think using using dictionary will be more efficient than list.the time complexity for dictionary is O(1) and for list it is O(n).

search = 'JR'
all_choices = Graduation.YEAR_IN_SCHOOL_CHOICES
dictionnary = {i[0]:i[1] for i in all_choices}
print(dictionnary[search])

Upvotes: 0

Pavan Kumar T S
Pavan Kumar T S

Reputation: 1559

You could write a function like below adn get it

 def get_choice(all_choices,search):
      for choice in all_choices:
        if choice[0] == search:
          return choice[1]
 return None    
 get_choice(all_choices,'JR')

Upvotes: 1

sudden_appearance
sudden_appearance

Reputation: 2195

Possible duplicate

Use

get_<field_name>_display()

Upvotes: 0

Related Questions