Python 2.7은 지원이 종료되었으며 2026년 1월 31일에 지원 중단됩니다. 지원 중단 후에는 조직에서 이전에 조직 정책을 사용하여 레거시 런타임의 배포를 다시 사용 설정한 경우에도 Python 2.7 애플리케이션을 배포할 수 없습니다. 기존 Python 2.7 애플리케이션은 지원 중단 날짜 이후에도 계속 실행되고 트래픽을 수신합니다. 지원되는 최신 Python 버전으로 마이그레이션하는 것이 좋습니다.
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')
Datastore에서 키에 사용할 ID를 생성하도록 허용
다음 코드는 자동 생성된 ID를 키로 사용하는 방법을 보여줍니다.
# 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.
키에서 상위 경로 사용
루트 항목으로 시작해서 상위에서 하위로 진행되고, 제공된 항목으로 이어지는 항목 시퀀스에 따라 항목의 상위 경로가 구성됩니다.
항목, 항목의 상위, 상위의 상위 등이 재귀적으로 항목의 상위가 됩니다. Datastore의 항목은 파일 시스템의 계층적 디렉터리 구조와 유사한 계층적 키 공간을 형성합니다.
항목을 식별하는 전체 키는 상위 경로를 지정하고 항목 자체로 끝나는 종류-식별자 쌍의 시퀀스로 구성됩니다. Key 클래스의 생성자 메서드는 이러한 종류와 식별자 시퀀스를 수락하고 해당 항목의 키를 나타내는 객체를 반환합니다.
다음 예는 메시지를 버전별로 저장하는 블로깅 서비스를 보여줍니다.
메시지는 계정 아래에 구성되며, 버전은 메시지 아래에 구성됩니다.
루트 항목의 경우, 상위 경로는 비어 있으며 키는 항목의 고유한 종류와 식별자로만 구성됩니다.
sandy_key=ndb.Key(Account,'sandy@example.com')
상위 항목이 있는 항목 지정
상위 키가 있는 새 메시지를 삽입하는 코드는 다음과 같습니다.
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()
상위 항목과 함께 키가 생성되면 parent() 메서드가 상위 항목을 나타내는 키를 반환합니다.
message_key=initial_revision.key.parent()
숫자 키 ID 사용
ID를 지정하지 않고 항목을 만들 수 있으며, 이 경우 데이터 스토어는 자동으로 숫자 ID를 생성합니다. 일부 ID를 지정한 후 Datastore가 자동으로 일부 ID를 생성하도록 선택하면 고유 키 요구 사항에 어긋날 수 있습니다. 이를 방지하려면 ID 선택 시 사용할 숫자 범위를 예약하세요. 또는 문자열 ID를 사용하면 이 문제를 완전히 방지할 수 있습니다.
ID 범위를 예약하려면 모델 클래스의 allocate_ids() 메서드를 사용하여 다음을 수행합니다.
지정된 수의 ID를 할당합니다.
모든 ID를 지정된 최대 값까지 할당합니다.
ID 할당
지정된 모델 클래스 MyModel에 100개의 ID를 할당하는 코드는 다음과 같습니다.
first,last=MyModel.allocate_ids(100)
상위 키 p가 있는 항목에 100개의 ID를 할당하는 코드는 다음과 같습니다.
first,last=MyModel.allocate_ids(100,parent=p)
반환된 first와 last 값은 할당된 첫 번째 ID와 마지막 ID입니다(경계 포함). 이 값을 사용하여 다음과 같이 키를 생성할 수 있습니다.
이러한 키는 데이터 저장소의 내부 ID 생성기에서 이전에 반환된 적이 없고 이후 내부 ID 생성기를 호출할 때 반환되지 않을 것이라고 보장됩니다. 하지만 allocate_ids() 메서드는 반환된 ID가 데이터 스토어에 있는지 여부를 확인하지 않으며 ID 생성기와만 상호 작용합니다.
모든 ID를 지정된 최대값까지 할당하는 코드는 다음과 같습니다.
first,last=MyModel.allocate_ids(max=N)
이 형태는 N보다 작거나 같은 모든 ID가 할당된 것으로 간주합니다. 반환된 first와 last 값은 이 작업으로 예약된 ID 범위를 나타냅니다. 이미 할당된 ID를 예약하려고 시도하는 것은 오류가 아닙니다. 그렇게 하면 first는 아직 할당되지 않은 최초의 ID를 나타내고 last는 할당된 마지막 ID가 됩니다.
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["이해하기 어려움","hardToUnderstand","thumb-down"],["잘못된 정보 또는 샘플 코드","incorrectInformationOrSampleCode","thumb-down"],["필요한 정보/샘플이 없음","missingTheInformationSamplesINeed","thumb-down"],["번역 문제","translationIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 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)."]]