当我尝试在 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__'
有没有一种方法可以在不使用点符号的情况下访问查询集中每个结果的属性?
最佳答案
当您使用[]
表示法时,Python将在内部尝试调用该对象上的__getitem__
方法。由于 Organism
对象没有定义该方法,因此它会失败并出现该错误。
相反,您可以使用 getattr
函数,像这样
print getattr(o, f)
如果对象中不存在该属性,您甚至可以指定要使用的默认值,如下所示
print getattr(o, f, "{} not present in {}".format(f, o))
关于python - Django:使用索引表示法而不是点表示法访问查询集的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29077512/