1

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.

3 Answers3

1

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')
Pavan Kumar T S
  • 1,539
  • 2
  • 17
  • 26
  • Okay, so I have to loop through the whole list. There is no way to do this without a full loop through the list? –  Feb 02 '22 at 15:27
  • well if you already have the object then you can use https://docs.djangoproject.com/en/4.0/ref/models/instances/#django.db.models.Model.get_FOO_display – Pavan Kumar T S Feb 02 '22 at 15:31
  • I don't have the object yet, I just have the "JR" string and want to find the matching item. –  Feb 02 '22 at 15:33
  • well then you have very limited options. if can change models create a model for your choices and make it a foreignkey. this way you could filter and get it easily – Pavan Kumar T S Feb 02 '22 at 15:36
  • OK well given the inability to change the model, I'll accept this answer. Looping through the options seems the only way to do this within my constraints. Thanks for the input! –  Feb 02 '22 at 19:24
0

Possible duplicate

Use

get_<field_name>_display()
sudden_appearance
  • 1,968
  • 1
  • 4
  • 15
0

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])
Thierno Amadou Sow
  • 2,523
  • 2
  • 5
  • 19