How to programmatically determine if ndb property is multivalue

偶尔善良 提交于 2019-12-30 10:58:29

问题


I am translating an app from Datastore to ndb and have encountered a problem in the xml import routine. The problem is that I am not able to programmatically determine whether a property of a ndb.model class is a multivalue property or not.

I suspect that this is due to lack of basic Python skills since the code I have come up with so far shows that the value is “visible”. I am thus not able to grab it. Please help.

from google.appengine.ext import ndb

class House(ndb.Model):
  name = ndb.StringProperty()   
  rooms = ndb.StringProperty(repeated=True) 

print 'Properties:'
for p in House._properties:
  print getattr(House,p)

print '\nRepeated:'
for p in House._properties:
  print getattr(getattr(House,p),'repeated',None)

This results in the following:

Properties:
StringProperty('rooms', repeated=True)
StringProperty('name')

Repeated:
None
None

回答1:


Actually, the underscore-prefixed options are the official API. It's a bug that they aren't documented, I will fix that. I explained a little more here: http://code.google.com/p/appengine-ndb-experiment/issues/detail?id=187

In particular, to get the properties of a model, you should use House._properties, not the code that Nick proposed. (In fact, __dict__ may be replaced with slots in future NDB versions.)




回答2:


NDB doesn't currently offer any options to introspect created models; you should definitely file a bug about this. In the meantime, poking into the object's internals is the only way to go about it. Be warned that this is very brittle, as internal implementation details can and will change at any time.

You can get a list of properties like this:

properties = [(k, v) for k, v in House.__dict__.items() if isinstance(v, ndb.Property)]

You can determine if a property is repeated by accessing the _repeated internal attribute on an instance - but see my disclaimer above for why this is probably a bad idea:

House.rooms._repeated

OR

getattr(House, 'rooms')._repeated


来源:https://stackoverflow.com/questions/10690418/how-to-programmatically-determine-if-ndb-property-is-multivalue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!