Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
Una instancia de la clase Key representa una clave de Datastore inmutable.
Esta página tiene documentación de referencia de API. Para obtener una descripción general, consulta Claves y entidades de NDB.
Introducción
Una Clave es una clave de Datastore inmutable. Las aplicaciones normalmente las usan para referirse a entidades. Cualquier entidad que se haya almacenado tiene una clave. A fin de obtener la clave de una entidad, usa la propiedad clave del modelo.
Para recuperar una entidad a partir de su clave, llama al método get() del objeto Key.
Las claves admiten comparaciones, por ejemplo, key1 == key2 o key1 < key2.
Estos operadores comparan el ID de aplicaciones, el espacio de nombres y la ruta de acceso principal completa. Usan el mismo orden que Datastore para realizar las consultas cuando ordena por propiedad de clave o por clave.
repr(key) o str(key) muestran la representación de una string similar al formulario de constructor más corto y omiten la app y el espacio de nombres, a menos que sean diferentes del valor predeterminado.
hash(key) funciona. Por lo tanto, puedes almacenar claves en una tabla de hash.
Constructores
Para mayor flexibilidad y conveniencia, se admiten varias firmas de constructores.
classKey(kind1, id1, kind2, id2, ...)
classKey(pairs=[(kind1, id1), (kind2, id2), ...])
classKey(flat=[kind1, id1, kind2, id2, ...])
classKey(urlsafe=string)
Los argumentos posicionales kind1, id1, kind2, id2... están en orden “principal”. (este es un acceso directo para flat=[kind1, id1,
kind2, id2]). Los valores principales preceden a los secundarios.
Los argumentos posicionales, pairs y los formularios de constructor flat también pueden pasar otra clave mediante superior=key. Los pares de superiores (kind, id) de la clave superior se insertan antes de que los pares se pasen de manera explícita (kind, id).
El parámetro de palabra clave urlsafe usa una referencia serializada codificada en base 64, pero es mejor considerarla como una string única opaca.
Argumentos de palabra clave de constructor adicionales:
app
Especifica el id de la aplicación (una string).
namespace
Especifica el espacio de nombres (una string).
Métodos de instancia que no afectan el Datastore
Con los siguientes métodos, se accede a los contenidos de una clave. No participan en ninguna actividad de E/S de Datastore.
pairs()
Muestra una tupla de pares (kind, id).
flat()
Muestra una tupla de similares acoplados y valores de id (kind1, id1, kind2, id2, …).
app()
Muestra el id de aplicación.
id()
Muestra la string o el ID de número entero en el último par (kind, id) o None si la clave está incompleta.
string_id()
Muestra el ID de string en el último par (kind, id) o None si la clave tiene un ID de número entero o está incompleta.
integer_id()
Muestra el ID de número entero en el último par (kind, id) o None si la clave tiene un ID de string o está incompleta.
namespace()
Muestra el espacio de nombres.
kind()
Muestra el tipo de similares en el último par (kind, id).
parent()
Muestra una clave construida a partir de todos los pares, excepto el último (kind, id) (o None si la clave tiene solo un par [kind, id]).
urlsafe()
Muestra una versión websafe-base64-encoded en serie de la clave.
Nota: La string segura para URL parece encriptada, pero no lo está.
Puede decodificarse con facilidad para recuperar el identificador y el tipo de similares de la entidad original.
to_old_key()
Muestra una Key para la API de Datastore "antigua" (db).
[[["Fácil de comprender","easyToUnderstand","thumb-up"],["Resolvió mi problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Información o código de muestra incorrectos","incorrectInformationOrSampleCode","thumb-down"],["Faltan la información o los ejemplos que necesito","missingTheInformationSamplesINeed","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Otro","otherDown","thumb-down"]],["Última actualización: 2025-09-04 (UTC)"],[[["\u003cp\u003eThis API for bundled services and \u003ccode\u003eKey\u003c/code\u003e class operations is specifically for first-generation runtimes in the App Engine standard environment, with migration to Python 3 requiring a specific guide.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003eKey\u003c/code\u003e class represents an immutable Datastore key, used to refer to entities and to retrieve them using the \u003ccode\u003eget()\u003c/code\u003e method.\u003c/p\u003e\n"],["\u003cp\u003eKeys can be compared using operators such as \u003ccode\u003e==\u003c/code\u003e and \u003ccode\u003e<\u003c/code\u003e, and also support string representation, as well as being used within a hash table.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003eKey\u003c/code\u003e class offers various constructor signatures, including those for ancestor order, pairs, flat structures, and URL-safe strings, along with options for specifying the application ID and namespace.\u003c/p\u003e\n"],["\u003cp\u003eThere are multiple methods to access key properties and contents, which do not affect the Datastore, as well as other methods that will interact with the Datastore, like to get or delete an entity.\u003c/p\u003e\n"]]],[],null,["# NDB Key Class\n\n| This page describes how to use the legacy bundled services and APIs. This API can only run in first-generation runtimes in the App Engine standard environment. If you are updating to the App Engine Python 3 runtime, refer to the [migration guide](/appengine/migration-center/standard/migrate-to-second-gen/python-differences) to learn about your migration options for legacy bundled services.\n\nAn instance of the `Key` class represents an immutable\nDatastore key.\n\nThis page has API reference documentation. For an overview,\nsee [NDB Entities and Keys](/appengine/docs/legacy/standard/python/ndb/creating-entities).\n\nIntroduction\n------------\n\nA Key is an immutable Datastore key. Applications normally use them to refer\nto entities. Any entity that has been stored has a key. To get an entity's\nkey, use the model's [key](/appengine/docs/legacy/standard/python/ndb/modelclass#Model_key)\nproperty.\nTo retrieve an entity from its key, call the `Key`\nobject's [get()](#Key_get) method.\n\nKeys support comparisons, for example\n\u003cvar translate=\"no\"\u003ekey1\u003c/var\u003e` == `\u003cvar translate=\"no\"\u003ekey2\u003c/var\u003e or\n\u003cvar translate=\"no\"\u003ekey1\u003c/var\u003e` \u003c `\u003cvar translate=\"no\"\u003ekey2\u003c/var\u003e.\nThese operators compare application ID, namespace, and the full\n\"ancestor path\". They use the same ordering as the Datastore uses\nfor queries when ordering by a key property or by key.\n\n`repr(`\u003cvar translate=\"no\"\u003ekey\u003c/var\u003e`)` or\n`str(`\u003cvar translate=\"no\"\u003ekey\u003c/var\u003e`)` returns\na string representation resembling\nthe shortest constructor form, omitting the app and namespace\nunless they differ from the default value.\n\n`hash(`\u003cvar translate=\"no\"\u003ekey\u003c/var\u003e`)` works. Thus, you can store keys in\na hash table.\n\nConstructors\n------------\n\nFor flexibility and convenience, multiple constructor signatures are\nsupported.\n\nclass Key(\u003cvar translate=\"no\"\u003ekind1\u003c/var\u003e, \u003cvar translate=\"no\"\u003eid1\u003c/var\u003e, \u003cvar translate=\"no\"\u003ekind2\u003c/var\u003e, \u003cvar translate=\"no\"\u003eid2\u003c/var\u003e, ...)\nclass Key(pairs=\\[(\u003cvar translate=\"no\"\u003ekind1\u003c/var\u003e, \u003cvar translate=\"no\"\u003eid1\u003c/var\u003e), (\u003cvar translate=\"no\"\u003ekind2\u003c/var\u003e, \u003cvar translate=\"no\"\u003eid2\u003c/var\u003e), ...\\])\nclass Key(flat=\\[\u003cvar translate=\"no\"\u003ekind1\u003c/var\u003e, \u003cvar translate=\"no\"\u003eid1\u003c/var\u003e, \u003cvar translate=\"no\"\u003ekind2\u003c/var\u003e, \u003cvar translate=\"no\"\u003eid2\u003c/var\u003e, ...\\])\nclass Key(urlsafe=\u003cvar translate=\"no\"\u003estring\u003c/var\u003e)\n\n: The positional arguments\n \u003cvar translate=\"no\"\u003ekind1\u003c/var\u003e, \u003cvar translate=\"no\"\u003eid1\u003c/var\u003e, \u003cvar translate=\"no\"\u003ekind2\u003c/var\u003e, \u003cvar translate=\"no\"\u003eid2\u003c/var\u003e...\n are in \"ancestor\" order. (This is a shortcut for\n `flat=[`\u003cvar translate=\"no\"\u003ekind1\u003c/var\u003e`, `\u003cvar translate=\"no\"\u003eid1\u003c/var\u003e`,\n `\u003cvar translate=\"no\"\u003ekind2\u003c/var\u003e`, `\u003cvar translate=\"no\"\u003eid2\u003c/var\u003e`]`) Parents come before children.\n\n The positional-arguments, `pairs`, and `flat`\n constructor forms can additionally pass in another\n key using parent=\u003cvar translate=\"no\"\u003ekey\u003c/var\u003e.\n The (\u003cvar translate=\"no\"\u003ekind\u003c/var\u003e, \u003cvar translate=\"no\"\u003eid\u003c/var\u003e) pairs of the parent key are\n inserted before the (\u003cvar translate=\"no\"\u003ekind\u003c/var\u003e, \u003cvar translate=\"no\"\u003eid\u003c/var\u003e) pairs\n passed explicitly.\n\n The `urlsafe` keyword parameter uses\n a websafe-base64-encoded serialized\n reference\n but it's best to think of it as just an opaque unique\n string.\n\n Additional constructor keyword arguments:\n\n app\n : specify the application id (a string)\n\n namespace\n : specify the namespace (a string)\n\nInstance Methods that Don't Affect the Datastore\n------------------------------------------------\n\nThe following methods access the contents of a key. They do not\nengage in any Datastore I/O activity.\n\npairs()\n\n: Returns a tuple of (kind, id) pairs.\n\nflat()\n\n: Returns a tuple of flattened kind and id values\n (kind1, id1, kind2, id2, ...).\n\napp()\n\n: Returns the application id.\n\nid()\n\n: Returns the string or integer id in the last (kind, id) pair,\n or `None` if the key is incomplete.\n\nstring_id()\n\n: Returns the string id in the last (kind, id) pair,\n or `None` if the key has an integer id or is incomplete.\n\ninteger_id()\n\n: Returns the integer id in the last (kind, id) pair,\n or `None` if the key has an string id or is incomplete.\n\nnamespace()\n\n: Returns the namespace.\n\nkind()\n\n: Returns the kind in the last (kind, id) pair.\n\nparent()\n\n: Returns a Key constructed from all but the last (kind, id) pair\n (or `None` if the key has just one (kind, id) pair).\n\nurlsafe()\n\n: Returns a websafe-base64-encoded serialized version of the key.\n\n **Note:**\n The URL-safe string looks cryptic, but it is not encrypted!\n It can easily be decoded to recover the original entity's kind and\n identifier.\n\nto_old_key()\n\n: Returns a\n [Key](/appengine/docs/legacy/standard/python/datastore/keyclass)\n for the \"old\" Datastore API (`db`).\n\nInstance Methods that Affect the Datastore\n------------------------------------------\n\nThese methods interact with the Datastore.\n\nget(\\*\\*ctx_options)\n\n: Returns the entity for the Key.\n\n **Arguments**\n\n \\*\\*ctx_options\n : [Context options](/appengine/docs/legacy/standard/python/ndb/functions#context_options)\n\nget_async(\\*\\*ctx_options)\n\n: Returns a\n [Future](/appengine/docs/legacy/standard/python/ndb/futureclass)\n whose eventual result is\n the entity for the Key.\n\n **Arguments**\n\n \\*\\*ctx_options\n : [Context options](/appengine/docs/legacy/standard/python/ndb/functions#context_options)\n\ndelete(\\*\\*ctx_options)\n\n: Delete the entity for the Key.\n\n **Arguments**\n\n \\*\\*ctx_options\n : [Context options](/appengine/docs/legacy/standard/python/ndb/functions#context_options)\n\ndelete_async(\\*\\*ctx_options)\n\n: Asynchronously delete the entity for the Key.\n\n **Arguments**\n\n \\*\\*ctx_options\n : [Context options](/appengine/docs/legacy/standard/python/ndb/functions#context_options)\n\nClass Methods\n-------------\n\nfrom_old_key(k)\n\n: Returns an NDB key from the passed in \"old\" Datastore API\n (`db`)\n [Key](/appengine/docs/legacy/standard/python/datastore/keyclass).\n\n **Arguments**\n\n \\*\\*ctx_options\n : [Context options](/appengine/docs/legacy/standard/python/ndb/functions#context_options)"]]