How to find out if a model class is db or a ndb

2019-07-29 07:22发布

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)

2条回答
贼婆χ
2楼-- · 2019-07-29 07:42

you could use an attribute that does exist only in ndb or the other way around.

for example _has_repeated or _pre_get_hook which are properties of the ndb entities.
so you could do:

self.ndb = hasattr(self, '_has_repeated')
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-07-29 08:07

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.
查看更多
登录 后发表回答