Reputation: 438
In the following code, I wish to iterate through all the variables of userData Object. I would like to know how to do it. The code, myString += eachObject.everyElement, is where I find the problem. I am not able to figure out how to iterate through every element of an object.
class userData(ndb.Model):
name = ndb.StringProperty()
age = ndb.IntegerProperty()
nationality = ndb.StringProperty()
date = ndb.DateTimeProperty()
class MyApp(webapp2.RequestHandler):
def post(self):
listOfUserData = ['name', 'age', 'nationality', 'date']
myString= ""
#Here, I have few userData objects and I wish to get all
#the userData perperties and form a string
myUserDataObjects = [userData1, userData2, userData3]
for eachObject in myUserDataObjects:
for everyElement in listOfUserData:
######################################
#This is the place where I need help##
######################################
myString += eachObject.everyElement
self.response.out.write(myString)
I know that I can access the elements by writing as eachObject.name + eachObject.age + ..., But I am against doing it, because if I do it and I plan to add a new property to the userData, I would have to change the code inside the for loop too. Rather I just plan to add that property to the listOfUserData which makes it easier.
Any suggestions/help is appreciated.
Thanks, Krishna Chaitanya
Upvotes: 2
Views: 760
Reputation: 5424
Use getattr method to get an attribute from an object. In your code sample, the following should work:
myString += getattr(eachObject, everyElement)
Upvotes: 2