Python 2.7은 지원이 종료되었으며 2026년 1월 31일에
지원 중단됩니다. 지원 중단 후에는 조직에서 이전에 조직 정책을 사용하여 레거시 런타임의 배포를 다시 사용 설정한 경우에도 Python 2.7 애플리케이션을 배포할 수 없습니다. 기존 Python 2.7 애플리케이션은
지원 중단 날짜 이후에도 계속 실행되고 트래픽을 수신합니다.
지원되는 최신 Python 버전으로 마이그레이션하는 것이 좋습니다.
PolyModel 클래스
컬렉션을 사용해 정리하기
내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요.
참고: 새로운 애플리케이션을 빌드하는 개발자는 NDB 클라이언트 라이브러리를 사용하는 것이 좋습니다. NDB 클라이언트 라이브러리는 이 클라이언트 라이브러리와 비교할 때 Memcache API를 통한 자동 항목 캐싱과 같은 여러 이점이 있습니다. 현재 이전 DB 클라이언트 라이브러리를 사용 중인 경우 DB에서 NDB로의 마이그레이션 가이드를 참조하세요.
PolyModel 클래스는 그 자체로 다른 데이터 모델 정의의 슈퍼클래스가 될 수 있는 데이터 모델 정의의 슈퍼클래스입니다. PolyModel 클래스에서 생성된 쿼리에는 클래스 또는 해당 서브클래스의 인스턴스인 결과가 포함될 수 있습니다.
PolyModel
는 google.appengine.ext.db.polymodel
모듈에서 제공됩니다.
PolyModel은 Model의 서브클래스이며 이 클래스에서 클래스와 인스턴스 메서드를 상속받습니다. PolyModel 클래스는 여러 Model 메서드를 재정의하지만 새로운 인터페이스 요소를 사용하지는 않습니다.
소개
데이터 모델을 분류 계층구조로 정의하면 유용한 경우가 많습니다. 이는 객체 데이터베이스가 하나의 객체 클래스를 다른 클래스의 서브클래스로 정의할 수 있는 것과 유사합니다. 이러한 데이터베이스는 상위 클래스의 객체를 대상으로 쿼리를 수행하고 결과에 서브클래스의 객체를 포함할 수 있습니다. App Engine Datastore는 기본적으로 이러한 종류의 쿼리를 지원하지 않지만 Python SDK에 포함된 메커니즘인 PolyModel
클래스를 사용하여 이를 구현할 수 있습니다.
PolyModel
에서 파생된 모델 클래스는 다른 모델 클래스의 기본 클래스가 될 수 있습니다. all()
및 gql()
메서드를 사용하여 이러한 클래스에 대해 생성된 쿼리는 결과에 서브클래스의 인스턴스를 포함할 수 있습니다.
서브클래스는 상위 클래스에 없는 새 속성을 정의할 수 있습니다. 하지만 서브클래스는 상위 클래스의 속성 정의를 재정의할 수 없습니다. 이렇게 하면 DuplicateProperty
오류가 발생합니다.
참고로, 항목 및 모델에서 가져온 간단한 다음 예를 살펴보세요. PolyModel
클래스가 google.appengine.ext.db.polymodel
패키지를 통해 제공되는 것을 확인할 수 있습니다.
from google.appengine.ext import db
from google.appengine.ext.db import polymodel
class Contact(polymodel.PolyModel):
phone_number = db.PhoneNumberProperty()
address = db.PostalAddressProperty()
class Person(Contact):
first_name = db.StringProperty()
last_name = db.StringProperty()
mobile_number = db.PhoneNumberProperty()
class Company(Contact):
name = db.StringProperty()
fax_number = db.PhoneNumberProperty()
p = Person(phone_number='1-206-555-9234',
address='123 First Ave., Seattle, WA, 98101',
first_name='Alfred',
last_name='Smith',
mobile_number='1-206-555-0117')
p.put()
c = Company(phone_number='1-503-555-9123',
address='P.O. Box 98765, Salem, OR, 97301',
name='Data Solutions, LLC',
fax_number='1-503-555-6622')
c.put()
for contact in Contact.all():
# Returns both p and c.
# ...
for person in Person.all():
# Returns only p.
# ...
다형성은 Datastore의 기본 기능이 아니며 PolyModel
클래스 자체에서 구현됩니다. PolyModel
서브클래스에서 생성되는 모든 항목이 같은 종류의 Datastore에 저장됩니다. 이때 종류는 루트 클래스 이름과 같습니다(예: Animal
). 각 객체는 클래스 계층구조를 'class'
라고 하는 항목의 멀티 값 속성으로 저장합니다. 앱이 PolyModel
클래스의 all()
또는 gql()
메서드를 사용하여 쿼리를 만들면 클래스 또는 모든 서브클래스에서 생성된 항목으로 결과를 제한하는 'class'
속성의 필터가 쿼리에 포함됩니다.
PolyModel
은 항목 속성을 사용하여 클래스 정보를 저장하므로 다형성 쿼리의 색인은 'class'
속성을 수용해야 합니다. 묵시적 필터는 균등 필터이며 다른 속성의 일치 필터 및 비일치 필터와 결합할 수 있습니다.
참고: PolyModel은 전체 경로가 아닌 'class'
속성의 클래스 이름만 사용합니다. A
→B
및 A
→C
→B
와 같이 이름이 같은 여러 노드를 사용하여 클래스 계층구조를 만들 수 있습니다. 이때 하나를 쿼리하면 둘 모두의 항목이 반환됩니다. 마찬가지로 A
→B
→C
를 쿼리하는 것과 A
→C
→B
를 쿼리하는 것은 기능적으로 동일합니다. 따라서 이름이 같은 여러 노드를 사용하여 단일 클래스 계층구조를 만들지 않는 것이 좋습니다.
PolyModel
은 서브클래스에서 속성 모델 정의를 재정의하는 작업을 지원하지 않습니다. 서브클래스가 슈퍼클래스에 정의된 속성을 다시 정의하려고 할 경우 클래스 정의가 DuplicatePropertyError
를 발생시킵니다.
PolyModel
은 슈퍼클래스를 공유하는 여러 클래스에서 상속받는 것을 포함하여 다중 상속을 지원합니다('다이아몬드' 상속). 클래스 하나는 각각 동일한 속성의 속성 모델 정의를 정의하는 클래스 두 개에서 상속받을 수 없습니다. 이렇게 하면 DuplicatePropertyError
가 발생합니다. 하지만 클래스 하나는 동일한 슈퍼클래스에서 동일한 속성 모델 정의를 상속받는 클래스 두 개에서 상속받을 수 있습니다.
PolyModel
은 Expando와 달리 동적 속성을 지원하지 않습니다. Expando
의 PolyModel
에 상응하는 요소는 없습니다.
생성자
PolyModel 클래스의 생성자는 다음과 같이 정의됩니다.
- class PolyModel(parent=None, key_name=None, **kwds)
-
다른 모델 클래스의 슈퍼클래스가 될 수 있으며 쿼리에 서브클래스의 인스턴스를 결과로 포함할 수 있는 모델 클래스입니다. Model과 마찬가지로 PolyModel 클래스는 데이터 항목의 종류를 정의하기 위해 서브클래스화되어야 합니다.
PolyModel은 Model의 서브클래스이며 해당 메서드를 상속받거나 재정의합니다.
인수
- parent
- 새 항목의 상위 요소인 항목의 모델 인스턴스 또는 키 인스턴스입니다.
- key_name
-
새 항목의 이름입니다. 이름은 기본 키에 포함됩니다. None
인 경우 시스템에서 생성된 ID가 키에 사용됩니다.
key_name 값은 숫자로 시작해서는 안 되고 __*__
형식이 아니어야 합니다. 애플리케이션이 사용자가 제출한 데이터(예: 이메일 주소)를 Datastore 항목 키 이름으로 사용하는 경우 이러한 요구사항을 충족하기 위해 애플리케이션이 먼저 'key:'과 같이 알려진 문자열을 접두사로 추가하여 값을 처리해야 합니다.
key_name
은 ASCII 텍스트로 변환된 str
값이 있는 유니코드 문자열로 저장됩니다.
- **kwds
- 인스턴스 속성의 초기 값이며 키워드 인수로 사용됩니다. 각 이름은 새 인스턴스의 속성과 일치하며, PolyModel 클래스에 정의된 고정 속성과 일치해야 합니다.
클래스 메서드
PolyModel 클래스는 Model 클래스에 정의되는 클래스 메서드 외에 다음과 같은 클래스 메서드도 제공합니다.
- PolyModel.class_key()
-
클래스 이름과 클래스의 모든 상위 클래스 이름을 튜플로 반환합니다.
- PolyModel.class_name()
-
클래스 이름을 반환합니다. Python 클래스의 이름이 변경되는 경우 클래스가 이 메서드를 재정의할 수 있지만 항목은 원래 클래스 이름을 계속 사용해야 합니다.
달리 명시되지 않는 한 이 페이지의 콘텐츠에는 Creative Commons Attribution 4.0 라이선스에 따라 라이선스가 부여되며, 코드 샘플에는 Apache 2.0 라이선스에 따라 라이선스가 부여됩니다. 자세한 내용은 Google Developers 사이트 정책을 참조하세요. 자바는 Oracle 및/또는 Oracle 계열사의 등록 상표입니다.
최종 업데이트: 2025-09-04(UTC)
[[["이해하기 쉬움","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\u003eThe \u003ccode\u003ePolyModel\u003c/code\u003e class allows for the creation of data model hierarchies, enabling queries to include instances of both the base class and its subclasses.\u003c/p\u003e\n"],["\u003cp\u003e\u003ccode\u003ePolyModel\u003c/code\u003e classes are stored in the datastore under the root class name, and each entity stores its class hierarchy in a \u003ccode\u003e'class'\u003c/code\u003e property, which is used for query filtering.\u003c/p\u003e\n"],["\u003cp\u003eSubclasses of \u003ccode\u003ePolyModel\u003c/code\u003e can introduce new properties but cannot override properties defined in parent classes, raising a \u003ccode\u003eDuplicatePropertyError\u003c/code\u003e if attempted.\u003c/p\u003e\n"],["\u003cp\u003ePolymorphic queries on \u003ccode\u003ePolyModel\u003c/code\u003e require indexes that include the \u003ccode\u003e'class'\u003c/code\u003e property and they support equality filters and can be combined with other filters.\u003c/p\u003e\n"],["\u003cp\u003e\u003ccode\u003ePolyModel\u003c/code\u003e supports multiple inheritance but not dynamic properties or \u003ccode\u003eExpando\u003c/code\u003e, and it's recommended to avoid multiple nodes with same name in class hierarchies.\u003c/p\u003e\n"]]],[],null,["# The PolyModel Class\n\n**Note:**\nDevelopers building new applications are **strongly encouraged** to use the\n[NDB Client Library](/appengine/docs/legacy/standard/python/ndb), which has several benefits\ncompared to this client library, such as automatic entity caching via the Memcache\nAPI. If you are currently using the older DB Client Library, read the\n[DB to NDB Migration Guide](/appengine/docs/legacy/standard/python/ndb/db_to_ndb)\n\nThe PolyModel class is the superclass for data model definitions that can themselves be superclasses for other data model definitions. A query produced from a PolyModel class can have results that are instances of the class or any of its subclasses.\n\n`PolyModel` is provided by the `google.appengine.ext.db.polymodel` module.\n\nPolyModel is a subclass of [Model](/appengine/docs/legacy/standard/python/datastore/modelclass), and inherits its class and instance methods from that class. The PolyModel class overrides several of Model's methods, but does not introduce any new interface elements.\n\nIntroduction\n------------\n\nIt is often useful to define data models as a classification hierarchy, much like how an object database can define one class of objects as a sub-class of another. Such a database can perform queries on objects of the parent class, and include objects of the sub-class in the results. The App Engine datastore does not support this kind of query natively, but you can implement it using a mechanism included with the Python SDK, the `PolyModel` class.\n\nA model class derived from `PolyModel` can be the base class for other model classes. Queries created for these classes using the `all()` and `gql()` methods know to include instances of subclasses in the results.\n\nSubclasses can define new properties not present on parent classes. However, subclasses cannot override property definitions of parent classes. (Doing so results in a `DuplicateProperty` error.)\n\nFor reference, here is the simple example from [Entities and Models](/appengine/docs/legacy/standard/python/datastore/datamodeling). Notice that the `PolyModel` class is provided by the package `google.appengine.ext.db.polymodel`. \n\n```python\nfrom google.appengine.ext import db\nfrom google.appengine.ext.db import polymodel\n\nclass Contact(polymodel.PolyModel):\n phone_number = db.PhoneNumberProperty()\n address = db.PostalAddressProperty()\n\nclass Person(Contact):\n first_name = db.StringProperty()\n last_name = db.StringProperty()\n mobile_number = db.PhoneNumberProperty()\n\nclass Company(Contact):\n name = db.StringProperty()\n fax_number = db.PhoneNumberProperty()\n\np = Person(phone_number='1-206-555-9234',\n address='123 First Ave., Seattle, WA, 98101',\n first_name='Alfred',\n last_name='Smith',\n mobile_number='1-206-555-0117')\np.put()\n\nc = Company(phone_number='1-503-555-9123',\n address='P.O. Box 98765, Salem, OR, 97301',\n name='Data Solutions, LLC',\n fax_number='1-503-555-6622')\nc.put()\n\nfor contact in Contact.all():\n # Returns both p and c.\n # ...\n\nfor person in Person.all():\n # Returns only p.\n # ...\n```\n\nPolymorphism is not a native feature of the datastore. Instead, polymorphism is implemented in the `PolyModel` class itself. All entities created from `PolyModel` subclasses are stored in the datastore with the same kind, which is the name of the root class (e.g. `Animal`). Each object stores its class hierarchy as a multi-valued property of the entity named `'class'`. When the app creates a query using a `PolyModel` class's `all()` or `gql()` method, the query includes a filter on the `'class'` property that limits the results to entities created from the class or any subclass.\n\nBecause `PolyModel` uses a property of the entity to store class information, indexes for polymorphic queries must accommodate the `'class'` property. The implied filter is an equality filter, and can be combined with other equality filters and inequality filters on other properties.\n\n**Note:** PolyModel uses just the names of the classes in the `'class'` property, not full paths. It's possible to create class hierarchies with multiple nodes of the same name, such as `A` → `B` and `A` → `C` → `B`. A query for one will return entities of both. Similarly, queries for `A` → `B` → `C` and `A` → `C` → `B` are functionally identical. It's best to avoid creating a single class hierarchy with multiple nodes of the same name.\n\n`PolyModel` does not support overriding property model definitions in subclasses. If a subclass tries to redefine a property that is defined on a superclass, the class definition raises a `DuplicatePropertyError`.\n\n`PolyModel` supports multiple inheritance, including inheriting from multiple classes that share a superclass (\"diamond\" inheritance). A class cannot inherit from two classes that each define a property model definition for the same property (this would raise a `DuplicatePropertyError`). However, a class can inherit from two classes that inherit the same property model definition from the same superclass.\n\n`PolyModel` does not support dynamic properties, like [Expando](/appengine/docs/legacy/standard/python/datastore/expandoclass) does. There is not an equivalent of `PolyModel` for `Expando`.\n\nConstructor\n-----------\n\nThe constructor of the PolyModel class is defined as follows:\n\nclass PolyModel(parent=None, key_name=None, \\*\\*kwds)\n\n: A model class that can be a superclass to other model classes, and whose queries can include instances of subclasses as results. Like [Model](/appengine/docs/legacy/standard/python/datastore/modelclass), the PolyModel class must be subclassed to define the kind of the data entities.\n\n PolyModel is a subclass of [Model](/appengine/docs/legacy/standard/python/datastore/modelclass), and inherits or overrides its methods.\n\n Arguments\n\n parent\n : The Model instance or Key instance for the entity that is the new entity's parent.\n\n key_name\n\n : The name for the new entity. The name becomes part of the primary key. If `None`, a system-generated ID is used for the key.\n\n The value for key_name must not start with a number, and must not be of the form `__*__`. If your application uses user-submitted data as datastore entity key names (such as an email address), the application should sanitize the value first, such as by prefixing it with a known string like \"key:\", to meet these requirements.\n\n A `key_name` is stored as a Unicode string, with `str` values converted as ASCII text.\n\n \\*\\*kwds\n : Initial values for the instance's properties, as keyword arguments. Each name corresponds with an attribute of the new instance, and must correspond with fixed properties defined in the PolyModel class.\n\nClass Methods\n-------------\n\nIn addition to the class methods defined by the [Model](/appengine/docs/legacy/standard/python/datastore/modelclass) class, the PolyModel class provides the following class methods:\n\nPolyModel.class_key()\n\n: Returns the name of the class and the names of all parent classes for the class, as a tuple.\n\nPolyModel.class_name()\n\n: Returns the name of the class. A class can override this method if the name of the Python class changes, but entities should continue using the original class name."]]