Django:使用索引表示法而不是点表示法访问查询集的属性?

时间:2015-03-16 13:02:57

标签: python django python-2.7

当我尝试在Django中执行此操作时:

organisms = Organism.objects.filter(code=c)
fields = ['name', 'linnean_type', 'age'] # in reality there are more
for o in organisms:
    for f in fields:
        print o[f]

我收到此错误:

TypeError 'Organism' object has no attribute '__getitem__'

有没有办法可以在不使用点表示法的情况下访问查询集中每个结果的属性?

1 个答案:

答案 0 :(得分:2)

在内部使用[]表示法时,Python将尝试在该对象上调用__getitem__方法。由于Organism对象没有定义该方法,因此失败并出现该错误。

相反,您可以使用getattr功能,就像这样

print getattr(o, f)

如果对象中不存在该属性,您甚至可以指定要使用的默认值,例如

print getattr(o, f, "{} not present in {}".format(f, o))
相关问题