简体   繁体   English

从django queryset获取django值,其中列名是一个变量

[英]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 我试图获取存储在数据库中的整数值,其中字典键与列名相同,并将其存储在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. 例如,在上面的循环中i.jan将返回我在一月份需要的值。

Cheers, Arthur 干杯,亚瑟

如果key='jan' ,并且想要获取obj.jan ,则可以使用Python的getattr

getattr(obj, key)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM