Arthur M
Arthur M

Reputation: 458

get django value from django queryset where column name is a variable

I have a database with some column names set up as abbreviated month names - the same as you see in this dictionary:

months = {'jan':0, 'feb':0, 'mar':0, 'apr':0, 'may':0, 'jun':0, 'jul':0, 'aug':0, 'sep':0, 'oct':0, 'nov':0, 'dec':0}

I'm trying to get the integer value stored in the db where the dictionary key is the same as the column name and store it in y

>>> for i in Somedb.objects.all():
...  for key, value in months.items():
...   y = i.key
... 
Traceback (most recent call last):
  File "<console>", line 3, in <module>
AttributeError: 'Somedb' object has no attribute 'x'

Anyone know how to do this? For example, in the above loop - i.jan would return the value I need for January.

Cheers, Arthur

Upvotes: 4

Views: 2522

Answers (1)

Alasdair
Alasdair

Reputation: 308779

If key='jan', and you want to get obj.jan, you can use Python's getattr.

getattr(obj, key)

Upvotes: 7

Related Questions