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

350
Visualizações
Django 1.4 - query iteration using fields stored in a dictionary

I had a huge registration table with 112 fields. For a particular search I want to compare 17 fields & assign colors to variable say 'clrSelected'. My code is :

reg = Regisration.objects.filter('some condition').order_by("name") 
for r in reg:
  if r.name=='abc': clrSelected='#fff'
  if r.type=='1': clrSelected='#000'
  if r.appl=='10': clrSelected='#c1ff51'
  if r.code=='': clrSelected='#60c5f7'
  if r.qlty=='first': clrSelected='#f99334'
  ...
  ...

there will be only one if condition, which need to be colored. Which means the field(from the dictionary) to be compared will change based on the user selection. I want to access the field name from a dictionary like this

flds = {'1':'name', '2':'type', '3':'appl', '4':'code', '5':'qlty',...}

And use it something like this

if r.flds['1']=='abc': clrSelected='#fff'

How could i use the fields as above. I am using django 1.4 & python 2.7

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

0

Just to answer the question, you could use getattr:

if getattr(r, flds['1']) == 'abc': clrSelected = '#fff'

However, I am pretty sure that you could go with a different kind of implementation in this case which doesn't require using a dict like this.

I would suggest using a three tuple list: (fieldName, value, color)

some_list  = [('name', 'abc', '#fff'), ('type', '1', '#000'), ...]

And, then use this list to determine the color:

for fieldName, value, color in some_list:
    if getattr(r, fieldName) == value:
        clrSelected = color

Looking at your implementation, it seems the color will be based on the last if condition which matches. If that is the case, you could create some_list in reverse order and break on the first matching condition.

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