如何确定模型类是 db 还是 ndb [英] How to find out if a model class is db or a ndb
本文介绍了如何确定模型类是 db 还是 ndb的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建了一个实用程序来交换或压缩所有实体为一种.但是我怎么知道使用的model_class是db.Model还是ndb.Model?
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
....
现在我使用:
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 的回答
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)
推荐答案
如何导入 ndb 和 db,并测试实体是它们各自 Model 类的实例?
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屋!
查看全文