I have a model class for eg.
class A(models.Model):
first = models.CharField(max_length=256)
def any_func(self):
string = 'first'
return self.string
Now if I call this function it shows me an error that
A does not have any field string
How to clear or correct this error
You need to use 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.
Here is an example:
>>> 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
will take a string, and if it is an attribute of the object, it will return that attribute (as if you did i.something
). The third argument is the default it should return if nothing was found.
I have a model class for eg.
class A(models.Model):
first = models.CharField(max_length=256)
def any_func(self):
string = 'first'
return self.string
Now if I call this function it shows me an error that
A does not have any field string
How to clear or correct this error
You need to use 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.
Here is an example:
>>> 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
will take a string, and if it is an attribute of the object, it will return that attribute (as if you did i.something
). The third argument is the default it should return if nothing was found.
0 commentaires:
Enregistrer un commentaire