Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

332
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda