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

221
Visualizações
django pass field-name as variable in get_or_create

I am trying to see if I can pass field name as a variable in get_or_create (since I have a function where the key in the kwargs can vary)

Like so:

def convert_value(cell_value, field_to_lookup):
        rem_obj, created = Rem.objects.get_or_create(field_to_lookup=cell_value)
        print ('created? ',created)
        return rem_obj

The above wont work since it would look for 'field_to_lookup' as the key.

This post suggests using getattr but not sure if that'll be applicable in this case since I will again need to assign the output to a variable

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

This post helped. Now passing the field-value pair as dict which allows passing variables for field names. Here's the code:

def convert_value(cell_value, field_to_lookup):
        rem_obj, created = Rem.objects.get_or_create(**{field_to_lookup:cell_value})
        print ('created? ',created)
        return rem_obj

Alternatively, I could directly just pass the dict to the function.

about 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