简体   繁体   中英

calling a field of a models in django

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 `xy`. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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