Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
Chaque entité est identifiée par une clé qui est unique dans l'instance Datastore de l'application et comprend les éléments suivants :
Genre – Il s'agit généralement du nom de la classe de modèle à laquelle appartient l'entité, mais vous pouvez le remplacer par une autre chaîne en ignorant la méthode de classe _get_kind().
Identifiant – Spécifiez votre propre nom de clé comme identifiant ou laissez Datastore générer automatiquement un ID numérique sous forme d'entier.
Spécifier votre propre nom de clé
L'exemple suivant permet de créer implicitement une clé avec un identifiant de chaîne à l'aide du paramètre nommé id :
Vous pouvez également définir le nom de clé directement :
account.key=ndb.Key('Account','sandy@example.com')# You can also use the model class object itself, rather than its name,# to specify the entity's kind:account.key=ndb.Key(Account,'sandy@example.com')
Laisser Datastore générer un ID qui servira de clé
Ce code montre comment utiliser un ID généré automatiquement comme clé :
# note: no id kwargaccount=Account(username='Sandy',userid=1234,email='sandy@example.com')account.put()# account.key will now have a key of the form: ndb.Key(Account, 71321839)# where the value 71321839 was generated by Datastore for us.
Utiliser le chemin d'ancêtre dans la clé
La séquence d'entités commençant par une entité racine, puis allant du parent à l'enfant pour arriver à une entité donnée, constitue le chemin d'ancêtre de cette entité.
Le parent, le parent du parent et ainsi de suite, sont les ancêtres d'une entité. Les entités du datastore forment donc un espace de clés structuré de manière hiérarchique, semblable à la structure de répertoires d'un système de fichiers.
La clé complète désignant l'entité se compose d'une séquence de paires genre/identifiant, qui spécifie son chemin d'ancêtre et se termine par les valeurs de l'entité elle-même. La méthode constructeur de la classe Key accepte ce type de séquence de genres et d'identifiants, et renvoie un objet représentant la clé de l'entité correspondante.
L'exemple suivant montre un service de création de blogs qui stocke des messages par révision.
Les messages sont regroupés par compte, et les révisions par message.
Dans l'exemple de code ci-dessus, ('Account', 'sandy@example.com'), ('Message', 123) et ('Revision', '1') sont tous des exemples de paires genre/identifiant.
Notez que Message n'est pas une classe de modèle. Il ne sert qu'à regrouper les révisions et non à stocker des données.
Comme indiqué dans l'exemple de code, le genre de l'entité est désigné par la dernière paire genre/nom de la liste : ndb.Key('Revision', '1').
Utiliser des paramètres nommés
Vous pouvez désigner directement une entité dans le chemin d'ancêtre au moyen du paramètre nommé parent. Les notations suivantes représentent toutes la même clé :
Dans le cas d'une entité racine, le chemin d'ancêtre est vide, et la clé n'est constituée que du genre et de l'identifiant de cette entité.
sandy_key=ndb.Key(Account,'sandy@example.com')
Spécifier une entité avec des ancêtres
Pour insérer un nouveau message avec des clés parentes :
account_key=ndb.Key(Account,'sandy@example.com')# Ask Datastore to allocate an ID.new_id=ndb.Model.allocate_ids(size=1,parent=account_key)[0]# Datastore returns us an integer ID that we can use to create the message# keymessage_key=ndb.Key('Message',new_id,parent=account_key)# Now we can put the message into Datastoreinitial_revision=Revision(message_text='Hello',id='1',parent=message_key)initial_revision.put()
Pour les clés créées avec un parent, la méthode parent() renvoie une clé représentant l'entité parente :
message_key=initial_revision.key.parent()
Utiliser des ID de clé numériques
Vous pouvez créer une entité sans spécifier d'ID, auquel cas le datastore génère automatiquement un ID numérique. Si vous choisissez de spécifier certains ID, puis que vous laissez Datastore en générer automatiquement d'autres, l'exigence d'unicité des clés risque de ne pas être respectée. Pour éviter que cela ne se produise, réservez une plage de nombres à utiliser comme ID. Sinon, l'emploi d'ID de chaîne permet de remédier complètement à ce problème.
Pour réserver une plage d'ID, utilisez la méthode de classe allocate_ids() de la classe de modèle :
pour allouer un nombre déterminé d'ID ;
pour allouer tous les ID jusqu'à une valeur maximale donnée.
Allouer des ID
Pour allouer 100 ID pour une classe de modèle donnée (MyModel) :
first,last=MyModel.allocate_ids(100)
Pour allouer 100 ID pour les entités ayant la clé parente p :
first,last=MyModel.allocate_ids(100,parent=p)
Les valeurs renvoyées, first et last, sont les premier et dernier ID (inclus) alloués. Vous pouvez vous en servir pour construire des clés comme suit :
Vous avez la garantie que ces clés n'ont pas déjà été renvoyées par le générateur d'ID internes du datastore et qu'elles ne seront pas renvoyées par des appels ultérieurs au générateur d'ID internes. Cependant, la méthode allocate_ids() ne vérifie pas si les ID renvoyés sont présents dans le datastore. Elle n'interagit qu'avec le générateur d'ID.
Pour allouer tous les ID jusqu'à une valeur maximale donnée :
first,last=MyModel.allocate_ids(max=N)
Ce formulaire garantit que tous les ID inférieurs ou égaux à N sont considérés comme alloués. Les valeurs renvoyées, first et last, indiquent la plage d'ID réservée par cette opération. La tentative de réservation d'ID déjà alloués n'entraîne pas une erreur. Si cela se produit, first indique le premier ID non encore alloué, et last est le dernier ID alloué.
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
Dernière mise à jour le 2025/09/04 (UTC).
[[["Facile à comprendre","easyToUnderstand","thumb-up"],["J'ai pu résoudre mon problème","solvedMyProblem","thumb-up"],["Autre","otherUp","thumb-up"]],[["Difficile à comprendre","hardToUnderstand","thumb-down"],["Informations ou exemple de code incorrects","incorrectInformationOrSampleCode","thumb-down"],["Il n'y a pas l'information/les exemples dont j'ai besoin","missingTheInformationSamplesINeed","thumb-down"],["Problème de traduction","translationIssue","thumb-down"],["Autre","otherDown","thumb-down"]],["Dernière mise à jour le 2025/09/04 (UTC)."],[[["\u003cp\u003eEntities in the Datastore are uniquely identified by a key, which includes a kind and an identifier, either specified by the user or automatically generated by Datastore.\u003c/p\u003e\n"],["\u003cp\u003eThe key identifier can be a string, set by the user, or an integer ID, automatically generated by Datastore, which can be chosen by either setting an \u003ccode\u003eid\u003c/code\u003e parameter or letting it be generated upon using \u003ccode\u003eput\u003c/code\u003e.\u003c/p\u003e\n"],["\u003cp\u003eEntities can have an ancestor path, forming a hierarchical structure similar to a file system, where the complete key includes a sequence of kind-identifier pairs representing the entity and its ancestors.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003eallocate_ids()\u003c/code\u003e method can be used to reserve a range of numeric IDs for a specific model, ensuring unique key creation, and this can be done either by specifying a number of ID's or a max number.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003eparent\u003c/code\u003e named parameter can be used to designate any entity in the ancestor path directly, offering flexibility in defining entity relationships and key structures.\u003c/p\u003e\n"]]],[],null,["# Creating and Using Entity Keys\n\n| This API is supported for first-generation runtimes and can be used when [upgrading to corresponding second-generation runtimes](/appengine/docs/standard/\n| python3\n|\n| /services/access). 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\nEach entity is identified by a key that is unique within the application's\nDatastore instance, and consists of the following:\n\n- **kind** . The kind is normally the name of the model class to which the entity belongs, but you can change this to some other string by overriding the classmethod `_get_kind()`.\n- **identifier** . You specify your own *key name* as the identifier or let Datastore automatically generate an integer numeric ID.\n\nSpecifying your own key name\n----------------------------\n\nThe following example implicitly creates a key with a string identifier\nusing the named parameter `id`: \n\n account = Account(\n username='Sandy', userid=1234, email='sandy@example.com',\n id='sandy@example.com')\n\n return account.key.id() # returns 'sandy@example.com'\n\nYou could alternatively set the key name directly: \n\n account.key = ndb.Key('Account', 'sandy@example.com')\n\n # You can also use the model class object itself, rather than its name,\n # to specify the entity's kind:\n account.key = ndb.Key(Account, 'sandy@example.com')\n\nLetting Datastore generate an ID to use for the key\n---------------------------------------------------\n\nThis code shows how to use an auto-generated ID as the key: \n\n # note: no id kwarg\n account = Account(username='Sandy', userid=1234, email='sandy@example.com')\n account.put()\n # account.key will now have a key of the form: ndb.Key(Account, 71321839)\n # where the value 71321839 was generated by Datastore for us.\n\nUsing the ancestor path in the key\n----------------------------------\n\nThe sequence of entities beginning with a root entity and proceeding from parent\nto child, leading to a given entity, constitute that entity's *ancestor path* .\nAn entity, its parent, parent's parent, and so on recursively, are the entity's\n*ancestors*. The entities in Datastore form a hierarchical key space\nsimilar to the hierarchical directory structure of a file system.\n\nThe complete key identifying an entity consists of a sequence of kind-identifier\npairs specifying its ancestor path and terminating with those of the entity\nitself. The constructor method for class `Key` accepts such a sequence of kinds and\nidentifiers and returns an object representing the key for the corresponding entity.\n\nThe following example shows a blogging service that stores messages by revision.\nMessages are organized under accounts, and revisions are under messages.\n\n\n class Revision(ndb.Model):\n message_text = ndb.StringProperty()\n\n`...` \n\n ndb.Key('Account', 'sandy@example.com', 'Message', 123, 'Revision', '1')\n ndb.Key('Account', 'sandy@example.com', 'Message', 123, 'Revision', '2')\n ndb.Key('Account', 'larry@example.com', 'Message', 456, 'Revision', '1')\n ndb.Key('Account', 'larry@example.com', 'Message', 789, 'Revision', '2')\n\nIn the sample, `('Account', 'sandy@example.com')`, `('Message', 123)`, and `('Revision', '1')`\nare all examples of kind-identifier pairs.\n\nNotice that `Message` is not a model class; it is used only as a way to group\nrevisions, not to store data.\n\nAs shown in the sample code, the entity's kind is designated by the *last*\nkind-name pair in the list: `ndb.Key('Revision', '1')`.\n\n### Using named parameters\n\nYou can use the named parameter `parent` to designate any entity in the ancestor\npath directly. All of the following notations represent the same key: \n\n ndb.Key('Account', 'sandy@example.com', 'Message', 123, 'Revision', '1')\n\n ndb.Key('Revision', '1', parent=ndb.Key(\n 'Account', 'sandy@example.com', 'Message', 123))\n\n ndb.Key('Revision', '1', parent=ndb.Key(\n 'Message', 123, parent=ndb.Key('Account', 'sandy@example.com')))\n\n### Specifying a root entity\n\nFor a root entity, the ancestor path is empty and the key consist solely of the\nentity's own kind and identifier. \n\n sandy_key = ndb.Key(Account, 'sandy@example.com')\n\n### Specifying an entity with ancestors\n\nTo insert a new message with parent keys \n\n account_key = ndb.Key(Account, 'sandy@example.com')\n\n # Ask Datastore to allocate an ID.\n new_id = ndb.Model.allocate_ids(size=1, parent=account_key)[0]\n\n # Datastore returns us an integer ID that we can use to create the message\n # key\n message_key = ndb.Key('Message', new_id, parent=account_key)\n\n # Now we can put the message into Datastore\n initial_revision = Revision(\n message_text='Hello', id='1', parent=message_key)\n initial_revision.put()\n\nFor keys that were created with a parent, the `parent()` method returns a key\nrepresenting the parent entity: \n\n message_key = initial_revision.key.parent()\n\nUsing Numeric Key IDs\n---------------------\n\nYou can create an entity without specifying an ID, in which case the data store\nautomatically generates a numeric ID. If you choose to specify some IDs and then\nlet Datastore automatically generate some IDs, you could\nviolate the requirement for unique keys. To avoid this, reserve a range of\nnumbers to use to choose IDs or use string IDs to avoid this issue entirely.\n\nTo reserve a range of IDs, use the model class'\n[`allocate_ids()`](/appengine/docs/legacy/standard/python/ndb/modelclass#Model_allocate_ids)\nclass method:\n\n- to allocate a specified number of IDs\n- to allocate all IDs up to a given maximum value.\n\n### Allocating IDs\n\nTo allocate 100 IDs for a given model class `MyModel`: \n\n first, last = MyModel.allocate_ids(100)\n\nTo allocate 100 IDs for entities with parent key `p`: \n\n first, last = MyModel.allocate_ids(100, parent=p)\n\nThe returned values, `first` and `last`, are the first and last IDs (inclusive)\nthat are allocated. You can use these to construct keys as follows: \n\n keys = [ndb.Key(MyModel, id) for id in range(first, last+1)]\n\nThese keys are guaranteed not to have been returned previously by the data\nstore's internal ID generator, nor will they be returned by future calls to the\ninternal ID generator. However, the `allocate_ids()` method does not check\nwhether the IDs returned are present in the data store; it only interacts with\nthe ID generator.\n\nTo allocate all IDs up to a given maximum value: \n\n first, last = MyModel.allocate_ids(max=N)\n\nThis form ensures that all IDs less than or equal to `N` are considered\nallocated. The return values, `first` and `last`, indicate the range of IDs\nreserved by this operation. It is not an error to attempt to reserve IDs already\nallocated; if that happens, `first` indicates the first ID not yet allocated and\n`last` is the last ID allocated.\n| **Note:** you cannot call `allocate_ids()` in a [transaction](/appengine/docs/legacy/standard/python/ndb/transactions)."]]