Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

320
Views
Get the name or labe from django IntegerChoices providing a valid value

I have django 3.2 and an IntegerChoices class

 class Type(models.IntegerChoices):
        GENERAL = 2, _("general address")
        DELIVERY = 4, _("delivery address")
        BILLING = 6, _("billing address")

I can get the Value name and label easily by doing Type.GENERAL , Type.GENERAL.name and Type.GENERAL.label.

But how can I get these values if I only have the value, e.g. I want to get the Name DELIVERY from the value 4.

Type[4].name ist not working as the list values does not correspond to the int values of the enum.

Thanks Matt

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

IntegerChoices.choices returns you a list of tuples with all content. In your case you'll have something like:

[(2, 'general address'), (4, 'delivery address'), (6, 'billing address')]

Thus it can be done this way:

class Type(models.IntegerChoices):
    GENERAL = 2, _("general address")
    DELIVERY = 4, _("delivery address")
    BILLING = 6, _("billing address")

def label_by_type_value(value):
    choices = [c[1] for c in Type.choices if c[0] == value]
    return choices[0] if len(choices) else None
over 4 years ago · Santiago Trujillo Report

0

You can also do something like this if you can be sure that it is a valid value:

print(Type(2).name)    
print(Type(2).label)
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!