views:

284

answers:

2
class Employee(db.Model):
  firstname           = db.StringProperty()       
  lastname            = db.StringProperty()       
  address1            = db.StringProperty() 
  timezone            = db.FloatProperty()     #might be -3.5 (can contain fractions)


class TestClassAttributes(webapp.RequestHandler):
  """
  Enumerate attributes of a db.Model class 
  """
  def get(self): 
     for item in Employee.properties(): 
         self.response.out.write("<br/>" + item)
         #for subitem in item.__dict__: 
         #   self.response.out.write("<br/>&nbsp;&nbsp;--" + subitem)

The above will give me a list of the property names for the variable "item". My idea of item.__dict__ didn't work because item was a str. How can I then display the data field type for each property, such as db.FloatProperty() for the property called timezone?

GAE = Google App Engine - but I'm sure the same answer would work for any class.

Thanks, Neal Walters

+2  A: 

Iterate using "for name, property in Employee.properties().items()". The property argument is the Property instance, which you can compare using instanceof.

Nick Johnson
+1  A: 

For problems like these, the interactive Python shell is really handy. If you had used it to poke around at your Employee object, you might have discovered the answer to your question through trial and error.

Something like:

>>> from groups.models import Group
>>> Group.properties()
{'avatar': <google.appengine.ext.db.StringProperty object at 0x19f73b0>,
 'created_at': <google.appengine.ext.db.DateTimeProperty object at 0x19f7330>,
 'description': <google.appengine.ext.db.TextProperty object at 0x19f7210>,
 'group_type': <google.appengine.ext.db.StringProperty object at 0x19f73d0>}

From that you know that the properties() method of a db.Model object returns a dict mapping the model's property names to the actual property objects they represent.

Will McCutchen
I believe that is what I showed in my question, i.e. I was iterating the properties(). I'm looking for how to get to the data type. I guess I could figure out anything with trial and error - thus the use of StackOverflow to save time.
NealWalters
I guess I was just trying to point out that dropping into the interactive shell might have pointed you in the right direction by showing you that the properties() method returns a dictionary, which you would (generally speaking, I think) want to iterate over differently (using .items() to get both the key and the value). And it would have shown you that the values stored in that dictionary are exactly the values you were looking for.
Will McCutchen