Google App Engine模型的自定义键(Python)

Cam*_*ron 12 python google-app-engine primary-key google-cloud-datastore

首先,我对Google App Engine比较陌生,所以我可能会做些傻事.

说我有一个模型Foo:

class Foo(db.Model):
   name = db.StringProperty()
Run Code Online (Sandbox Code Playgroud)

我想name用作每个Foo对象的唯一键.这是怎么做到的?

当我想获得一个特定的Foo对象时,我目前在数据存储区中查询Foo具有目标唯一名称的所有对象,但查询速度很慢(另外,确保nameFoo创建每个新对象时它是唯一的).

必须有一个更好的方法来做到这一点!

谢谢.

Wil*_*hen 13

我之前在项目中使用过以下代码.只要您需要以您的密钥名称为基础的字段,它就会起作用.

class NamedModel(db.Model):
    """A Model subclass for entities which automatically generate their own key
    names on creation. See documentation for _generate_key function for
    requirements."""

    def __init__(self, *args, **kwargs):
        kwargs['key_name'] = _generate_key(self, kwargs)
        super(NamedModel, self).__init__(*args, **kwargs)


def _generate_key(entity, kwargs):
    """Generates a key name for the given entity, which was constructed with
    the given keyword args.  The entity must have a KEY_NAME property, which
    can either be a string or a callable.

    If KEY_NAME is a string, the keyword args are interpolated into it.  If
    it's a callable, it is called, with the keyword args passed to it as a
    single dict."""

    # Make sure the class has its KEY_NAME property set
    if not hasattr(entity, 'KEY_NAME'):
        raise RuntimeError, '%s entity missing KEY_NAME property' % (
            entity.entity_type())

    # Make a copy of the kwargs dict, so any modifications down the line don't
    # hurt anything
    kwargs = dict(kwargs)

    # The KEY_NAME must either be a callable or a string.  If it's a callable,
    # we call it with the given keyword args.
    if callable(entity.KEY_NAME):
        return entity.KEY_NAME(kwargs)

    # If it's a string, we just interpolate the keyword args into the string,
    # ensuring that this results in a different string.
    elif isinstance(entity.KEY_NAME, basestring):
        # Try to create the key name, catching any key errors arising from the
        # string interpolation
        try:
            key_name = entity.KEY_NAME % kwargs
        except KeyError:
            raise RuntimeError, 'Missing keys required by %s entity\'s KEY_NAME '\
                'property (got %r)' % (entity.entity_type(), kwargs)

        # Make sure the generated key name is actually different from the
        # template
        if key_name == entity.KEY_NAME:
            raise RuntimeError, 'Key name generated for %s entity is same as '\
                'KEY_NAME template' % entity.entity_type()

        return key_name

    # Otherwise, the KEY_NAME is invalid
    else:
        raise TypeError, 'KEY_NAME of %s must be a string or callable' % (
            entity.entity_type())
Run Code Online (Sandbox Code Playgroud)

然后,您可以像这样修改示例模型:

class Foo(NamedModel):
    KEY_NAME = '%(name)s'
    name = db.StringProperty()
Run Code Online (Sandbox Code Playgroud)

当然,这可以大大简化你的情况,改变了第一线NamedModel__init__方法是这样的:

kwargs['key_name'] = kwargs['name']
Run Code Online (Sandbox Code Playgroud)

  • 啊,这看起来很酷但有点矫枉过正.无论如何,它仍然让我走上了正确的轨道,发现了我所缺少的东西:关于key_name的知识!这是一切的关键:-) (3认同)