我创建了一个实用程序来交换或压缩所有实体的一种。但是我怎样才能知道使用的 model_class 是 db.Model 还是 ndb.Model?
def _encode_entity(self, entity):
if self.ndb :
entity_dict = entity.to_dict()
self.entity_eid = entity.key.id()
entity_dict['NDB'] = True
else :
entity_dict = db.to_dict(entity)
self.entity_eid = entity.key().name()
entity_dict['NDB'] = False
....
现在我使用:
def queryKind(self):
try :
self.query = self.model_class.query()
self.ndb = True
except AttributeError :
self.query = self.model_class.all()
self.ndb = False
return self.make(self._encode_entity) # make a zip or a page
更新:我使用的解决方案。另见Guido的回答
self.kind = 'Greeting'
module = __import__('models', globals(), locals(), [self.kind], -1)
self.model_class = getattr(module, self.kind)
entity = self.model_class()
if isinstance(entity, ndb.Model):
self.ndb = True
self.query = self.model_class.query()
elif isinstance(entity, db.Model):
self.ndb = False
self.query = self.model_class.all()
else :
raise ValueError('Failed to classify entities of kind : ' + self.kind)