Search code examples
djangogetattr

django: getattr function (get field name)


I can't make the function getattr work. Here is my code:

print ConfigConsModel()._meta.get_all_field_names() #['codesectrepmodel', 'configCons', 'id']
modelInstance=ConfigConsModel()
newAttrName1=getattr(modelInstance, "configCons")
print newAttrName1 #empty -> PB

What's wrong?


Solution

  • modelInstance=ConfigConsModel()
    

    This initializes modelInstance as new (empty) instance of ConfigConsModel class

    newAttrName1=getattr(modelInstance, "configCons")
    

    This line is equivalent to

    newAttrName1=modelInstance.configCons
    

    It does not get attribute's name, it gets it's value. Which of course is empty.