如何确定模型类是db还是ndb

时间:2013-01-09 16:25:38

标签: google-app-engine google-cloud-datastore app-engine-ndb

我创建了一个实用程序来交换或压缩所有实体。但是,如何确定使用的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)

2 个答案:

答案 0 :(得分:5)

您可以使用仅在ndb或其他方面存在的属性。

例如_has_repeated_pre_get_hook,它们是ndb实体的属性 所以你可以这样做:

self.ndb = hasattr(self, '_has_repeated')

答案 1 :(得分:5)

如何导入ndb和db,并测试实体是否为各自Model类的实例?

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.