如何找出模型类是db还是ndb [英] How to find out if a model class is db or a ndb
本文介绍了如何找出模型类是db还是ndb的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建了一个实用程序来交换或压缩所有实体。但是我怎么能找出model_class是一个db.Model还是一个ndb.Model?
def _encode_entity(self,实体):
如果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'] =假
....
现在我使用:
def queryKind(self):
try:
self.query = self.model_class.query( )
self.ndb = True
除了AttributeError:
self.query = self.model_class.all()
self.ndb = False
return self.make self._encode_entity)#make a zip or a page
self.kind ='问候'
模块= __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:
提高ValueError('未能对实体进行分类:'+ self.kind)
解决方案
如何导入ndb和db,并测试实体它们各自的Model类的实例?
pre $ if isinstance(entity,ndb.Model):
# NDB方式。
elif isinstance(entity,db.Model):
#使用db方式。
else:
#失败。不是一个实体。
I created a utility to exchange or zip all the entities for a kind. But how can I find out if the model_class used is a db.Model or an 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
....
Now I use :
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
UPDATE : The solution I have used. See also Guido's answer
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)
解决方案
How about import ndb and db, and testing for the entity being an instance of their respective Model classes?
if isinstance(entity, ndb.Model):
# Do it the NDB way.
elif isinstance(entity, db.Model):
# Do it the db way.
else:
# Fail. Not an entity.
这篇关于如何找出模型类是db还是ndb的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文