Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

349
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda