我有一个模型类,例如。
class A(models.Model):
first = models.CharField(max_length=256)
def any_func(self):
string = 'first'
return self.string
现在,如果我调用此函数,它会向我显示错误
A没有任何字段字符串
如何清除或更正此错误
答案 0 :(得分:0)
您需要使用getattr
:
getattr(...)
`getattr(object, name[, default]) -> value` Get a named attribute from an object; `getattr(x, 'y')` is equivalent to `x.y`. When a default argument is given, it is returned when the attribute doesn't exist; without it, an exception is raised in that case.
以下是一个例子:
>>> class A(object):
... def __init__(self, foo):
... self.bar = foo
... def get_stuff(self, stuff):
... return getattr(self, stuff, 'Not Found')
...
>>> i = A('hello')
>>> i.get_stuff('zoo')
'Not Found'
>>> i.get_stuff('bar')
'hello'
getattr
将获取一个字符串,如果它是该对象的一个属性,它将返回该属性(就像您执行i.something
一样)。第三个参数是如果没有找到则应该返回的默认值。