Python Inspect - 查找 GAE db.model 类中属性的数据类型
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/> --" + subitem)
上面将为我提供变量“item”的属性名称列表。 我的 item.__dict__
想法不起作用,因为 item
是一个 str
。 然后,如何显示每个属性的数据字段类型,例如名为 timezone
的属性的 db.FloatProperty()
?
GAE = Google App Engine - 但我确信相同的答案适用于任何课程。
谢谢, 尼尔·沃尔特斯
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/> --" + 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用“for name, property in Employee.properties().items()”进行迭代。 property 参数是 Property 实例,您可以使用 instanceof 对其进行比较。
Iterate using "for name, property in Employee.properties().items()". The property argument is the Property instance, which you can compare using instanceof.
对于此类问题,交互式 Python shell 非常方便。如果您使用它来查看 Employee 对象,您可能已经通过反复试验找到了问题的答案。
类似这样的:
从中您知道
db.Model
对象的properties()
方法返回一个dict
将模型的属性名称映射到它们代表的实际财产对象。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 that you know that the
properties()
method of adb.Model
object returns adict
mapping the model's property names to the actual property objects they represent.我添加了同样的问题,前两个答案并没有100%帮助我。
我无法从类的元数据或
实例属性,这很奇怪。所以我不得不使用字典。
GetType() 方法将以字符串形式返回属性的类型。
这是我的回答:
I add the same problem, and the first 2 answers did not help me 100%.
I was not able to get the type information, from the meta data of the class or the
instance property, which is bizarre. So I had to use a dictionary.
The method GetType() will return the type of the property as a string.
Here is my answer: