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

12 投票
2 回答
4322 浏览
提问于 2025-04-15 20:32

首先,我对Google App Engine还比较陌生,所以可能做了一些傻事。

假设我有一个模型叫做Foo:

class Foo(db.Model):
   name = db.StringProperty()

我想用name作为每个Foo对象的唯一标识。这个怎么实现呢?

现在,当我想获取一个特定的Foo对象时,我会在数据存储中查询所有具有目标唯一名称的Foo对象,但查询速度很慢(而且在每次创建新的Foo时,确保name是唯一的也很麻烦)。

肯定有更好的方法来做到这一点!

谢谢。

2 个回答

2

这里有一篇关于AppEngine数据存储中唯一性问题的详细讨论:我该如何为Google App Engine中的模型定义一个唯一属性?

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())

然后你可以像这样修改你的示例模型:

class Foo(NamedModel):
    KEY_NAME = '%(name)s'
    name = db.StringProperty()

当然,在你的情况下,这可以大大简化,只需把NamedModel__init__方法的第一行改成类似这样的内容:

kwargs['key_name'] = kwargs['name']

撰写回答