django: getattr function (get field name)

rom picture rom · Jul 25, 2013 · Viewed 8.6k times · Source

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?

Answer

vartec picture vartec · Jul 25, 2013
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.