简体   繁体   中英

Repeated subclasses of ndb properties

I have create a subclass of ndb.KeyProperty that can accept keys, but also entities or base 64 key strings and convert them to keys. It works great, except when I try create a repeated property.

Basically my code is this:

def to_key(target):
    if isinstance(target, ndb.Model):
        target_key = target.key
    elif isinstance(target, ndb.Key):
        target_key = target
    else:
        try:
            target_key = ndb.Key(urlsafe=target)
        except:
            raise TypeError('%s is not an ndb instance or key' % target)
    return target_key

class AutoKeyProperty(ndb.KeyProperty):
    def _validate(self, value):
        return to_key(value)

Handling iterable values in _validate just moves to the problem down to the base ndb.KeyProperty class.

The right function you need to override is _to_base_type . This function convert an input value into an instance of property's type, in your case a Key. So your AutoKeyProperty class would look like this:

class AutoKeyProperty(ndb.KeyProperty):
    def _to_base_type(self, value):
        return to_key(value)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM