Python 2.7은 지원이 종료되었으며 2026년 1월 31일에
지원 중단됩니다. 지원 중단 후에는 조직에서 이전에 조직 정책을 사용하여 레거시 런타임의 배포를 다시 사용 설정한 경우에도 Python 2.7 애플리케이션을 배포할 수 없습니다. 기존 Python 2.7 애플리케이션은
지원 중단 날짜 이후에도 계속 실행되고 트래픽을 수신합니다.
지원되는 최신 Python 버전으로 마이그레이션하는 것이 좋습니다.
Property 클래스
컬렉션을 사용해 정리하기
내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요.
참고: 새로운 애플리케이션을 빌드하는 개발자는 NDB 클라이언트 라이브러리를 사용하는 것이 좋습니다. NDB 클라이언트 라이브러리는 이 클라이언트 라이브러리와 비교할 때 Memcache API를 통한 자동 항목 캐싱과 같은 여러 이점이 있습니다. 현재 이전 DB 클라이언트 라이브러리를 사용 중인 경우 DB에서 NDB로의 마이그레이션 가이드를 참조하세요.
Property 클래스는 데이터 모델에 대한 속성 정의의 상위 클래스입니다. Property 클래스는 속성 값의 유형, 값의 유효성 검사 방법, Datastore에 값이 저장되는 방법을 정의합니다.
Property
는 google.appengine.ext.db
모듈에서 제공됩니다.
소개
속성 클래스는 값 유형, 기본값, 유효성 검사 논리, 모델 속성의 기타 기능을 설명합니다. 각 속성 클래스는 Property 클래스의 하위 클래스입니다. Datastore API에는 각 Datastore 값 유형에 대한 속성 클래스와 Datastore 유형과 더불어 추가 기능을 제공하는 여러 속성 클래스를 포함합니다. 유형 및 속성 클래스를 참조하세요.
속성 클래스는 생성자에게 전달된 인수의 구성을 허용할 수 있습니다. 기본 클래스 생성자는 Datastore API에 제공된 모든 인수를 비롯해 일반적으로 모든 속성 클래스에서 지원되는 여러 인수를 지원합니다. 이러한 구성에는 기본값, 명시적 값의 필요 여부, 허용되는 값 목록, 커스텀 유효성 검사 로직이 포함됩니다. 속성 구성에 대한 자세한 내용은 특정 속성 유형 문서를 참조하세요.
속성 클래스는 데이터 저장소 속성의 모델을 정의하지만 모델 인스턴스의 속성 값은 포함하지 않습니다. Property 클래스의 인스턴스는 클래스의 인스턴스가 아니라 모델 클래스에 속합니다. Python 용어로 속성 클래스 인스턴스는 모델 인스턴스의 속성이 어떻게 동작하는지 정의하는 '설명자'입니다. 설명자에 대한 자세한 내용은 Python 문서를 참조하세요.
생성자
Property 기본 클래스의 생성자는 다음과 같이 정의됩니다.
- class Property(verbose_name=None, name=None, default=None, required=False, validator=None, choices=None, indexed=True)
-
모델 속성 정의의 상위 클래스입니다.
인수
- verbose_name
- 사용자 친화적인 속성 이름으로 항상 속성 생성자에 대한 첫 번째 인수여야 합니다.
djangoforms
라이브러리는 이 이름을 사용하여 양식 필드 라벨을 만듭니다. 다른 곳에서도 비슷한 용도로 사용할 수 있습니다.
- name
- 쿼리에 사용되는 속성의 저장소 이름입니다. 이 이름은 속성에 대한 특성(attribute) 이름의 기본값으로 사용됩니다. 모델 클래스는 속성(property) 외에 특성(attribute) 또한 가지기 때문에 속성은 이름을 사용하여 예약된 특성 이름을 Datastore의 속성 이름으로 사용하고, 속성의 특성(property attribute)에 대해서는 다른 이름을 사용할 수 있습니다. 자세한 내용은 허용되지 않는 속성 이름을 참조하세요.
- default
-
속성의 기본값입니다. 속성에 값이 제공되지 않거나 None
값이 제공된 경우, 이 값이 기본값으로 간주됩니다.
참고: 모델 클래스 정의는 나머지 애플리케이션 코드와 함께 캐시됩니다. 여기에는 속성의 기본값 캐싱이 포함됩니다. users.get_current_user()
와 같은 요청에 지정된 데이터를 사용하여 모델 정의의 기본값을 설정하지 마세요. 대신 속성 값을 초기화하는 Model 클래스의 __init__()
메서드를 정의하세요.
- required
-
True
인 경우 속성은 None
값을 가질 수 없습니다. 모델 인스턴스는 누락된 값으로 인스턴스가 작성되지 않도록 생성자의 모든 필수 속성을 초기화해야 합니다. 필수 속성을 초기화하지 않고 인스턴스 생성을 시도하거나 필수 속성에 None
값을 할당하려고 시도하면 BadValueError가 발생합니다.
필수이며 기본값이 있는 속성은 생성자에 속성이 지정되지 않은 경우 기본값을 사용합니다. 그러나 속성에는 None
값을 할당할 수 없으며 다른 값이 할당된 후에는 기본값을 자동으로 복구할 수 있는 방법이 없습니다. 항상 속성의 default
에 액세스하여 이 값을 가져와서 명시적으로 할당할 수 있습니다.
- validator
- 값이 할당되었을 때 속성의 값을 검사하기 위해 호출해야 하는 함수입니다. 이 함수는 값을 유일한 인수로 사용하고 값이 유효하지 않은 경우 예외를 발생시킵니다. 지정된 검사기는 다른 검사(예: 필수 속성이 값을 가지는지 확인하는 검사)가 끝난 후에 호출됩니다. 필수가 아닌 속성에 값이 지정되지 않은 경우, 검사기는
None
인수와 함께 호출됩니다.
- choices
- 속성에 허용되는 값의 목록입니다. 옵션이 설정된 경우 속성에 목록에 없는 값을 할당할 수 없습니다. required 및 기타 유효성 검사와 마찬가지로 모델 인스턴스는 유효하지 않은 값으로 인스턴스가 작성되지 않도록 모든 속성과 옵션을 초기화해야 합니다. choices가
None
이면 유효성 검사를 통과한 모든 값이 허용됩니다.
- indexed
-
이 속성이 개발자가 정의한 내장 색인에 포함되어야 하는지를 나타냅니다. False
이면 Blob 및 Text 속성과 유사하게, Datastore에 작성된 항목이 이 속성을 기준으로 정렬하거나 필터링하는 쿼리에 의해 반환되지 않습니다.
참고: 색인이 생성된 모든 속성은 put()
및 delete()
호출에 약간의 오버헤드, CPU 비용, 지연 시간이 추가됩니다. 속성을 필터링하거나 정렬할 필요가 없는 경우 오버헤드를 피하려면 indexed=False
사용을 고려해 보세요. 이 경우 주의해야 합니다. 나중에 속성 색인을 생성하기로 결정하고 indexed=True
로 되돌리면, 되돌린 이후의 쓰기에만 영향을 주기 때문입니다. 원래 indexed=False
로 작성된 항목의 색인은 다시 생성할 수 없습니다.
클래스 속성
Property 클래스의 하위 클래스는 다음과 같은 클래스 속성을 정의합니다.
data_type
- Python 고유 값으로 허용되는 Python 데이터 유형 또는 클래스입니다.
인스턴스 메서드
Property 클래스의 인스턴스에는 다음과 같은 메서드가 있습니다.
- default_value()
-
속성의 기본값을 반환합니다. 이 메서드의 기본 구현에서는 생성자에 전달된 기본 인수 값을 사용합니다. 속성 클래스는 이 값을 재정의하여 DateTimeProperty의 auto-now 기능과 같은 특별한 기본값 동작을 제공합니다.
- validate(value)
-
속성에 대한 완전한 유효성 검사 루틴입니다. 값이 유효한 경우 변경되지 않은 값 또는 필수 유형에 맞는 값을 반환합니다. 유효하지 않은 경우에는 적절한 예외가 발생합니다.
기본 구현에서는 value가 필수인 경우 None
이 아닌지 확인하고(기본 Property 생성자에 대한 required 인수), 속성이 옵션으로 구성된 경우 값이 유효한 옵션 중 하나인지를 확인하고(choices 인수), 값이 커스텀 검사기(있는 경우)를 전달하는지 확인합니다(validator 인수).
유효성 검사 루틴은 속성 유형을 사용하는 모델이 기본값 또는 초기화된 값으로 인스턴스화되고 유형의 속성에 값이 할당될 때 호출됩니다. 이 루틴은 부작용이 없습니다.
- empty(value)
-
value가 속성 유형의 빈 값으로 간주되는 경우 True
를 반환합니다. 기본 구현은 대부분 유형에 충분한 not value
와 동일합니다. 부울 유형을 비롯한 다른 유형에서는 이 메서드를 적절한 테스트로 대체할 수 있습니다.
- get_value_for_datastore(model_instance)
-
지정된 모델 인스턴스 내의 이 속성에 대해 Datastore에 저장해야 하는 값을 반환합니다. 이 메서드의 기본 구현은 모델 인스턴스 내의 Python 고유의 속성 값을 반환하는 것입니다. 속성 클래스는 모델 인스턴스 대신 Datastore에 대해 다른 데이터 유형을 사용하거나, 모델 인스턴스를 저장하기 직전에 다른 데이터 변환을 수행하도록 이 값을 재정의할 수 있습니다.
- make_value_from_datastore(value)
-
Datastore에서 지정된 값의 Python 고유 표현을 반환합니다. 이 메서드의 기본 구현은 단순히 값을 반환하는 것입니다. 속성 클래스는 모델 인스턴스 대신 Datastore에 대해 다른 데이터 유형을 재정의할 수 있습니다.
- make_value_from_datastore_index_value(value)
-
Datastore 색인에서 지정된 값의 Python 고유 표현을 반환합니다. 이 메서드의 기본 구현은 단순히 값을 반환하는 것입니다. 속성 클래스는 모델 인스턴스 대신 Datastore에 대해 다른 데이터 유형을 재정의할 수 있습니다.
달리 명시되지 않는 한 이 페이지의 콘텐츠에는 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\u003eDevelopers should utilize the NDB Client Library for new applications due to its advantages, such as automatic entity caching.\u003c/p\u003e\n"],["\u003cp\u003eThe Property class, found in \u003ccode\u003egoogle.appengine.ext.db\u003c/code\u003e, serves as the foundation for defining data model properties, including their type, validation, and storage method.\u003c/p\u003e\n"],["\u003cp\u003eA Property class instance is a descriptor within a Model class, dictating the behavior of Model instance attributes but not storing the property's value for each specific model.\u003c/p\u003e\n"],["\u003cp\u003eThe Property class constructor allows for configuring properties with settings like default values, requirement status, validation rules, acceptable choices, and whether they are indexed for queries.\u003c/p\u003e\n"],["\u003cp\u003eProperty class instances offer methods such as \u003ccode\u003evalidate()\u003c/code\u003e, \u003ccode\u003eempty()\u003c/code\u003e, \u003ccode\u003eget_value_for_datastore()\u003c/code\u003e, and more, which define how values are handled, validated, and stored in the datastore.\u003c/p\u003e\n"]]],[],null,["# The Property 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 Property class is the superclass of property definitions for data models. A Property class defines the type of a property's value, how values are validated, and how values are stored in the datastore.\n\n`Property` is provided by the `google.appengine.ext.db` module.\n\nIntroduction\n------------\n\nA property class describes the value type, default value, validation logic and other features of a property of a [Model](/appengine/docs/legacy/standard/python/datastore/modelclass). Each property class is a subclass of the Property class. The datastore API includes property classes for each of the datastore value types, and several others that provide additional features on top of the datastore types. See [Types and Property Classes](/appengine/docs/legacy/standard/python/datastore/typesandpropertyclasses).\n\nA property class can accept configuration from arguments passed to the constructor. The base class constructor supports several arguments that are typically supported in all property classes, including all those provided in the datastore API. Such configuration can include a default value, whether or not an explicit value is required, a list of acceptable values, and custom validation logic. See the documentation for a specific property type for more information on configuring the property.\n\n\nA property class defines the model for a datastore property. It does not contain the property value for a model instance. Instances of the Property class belong to the Model class, not instances of the class. In Python terms, property class instances are \"descriptors\" that customize how attributes of Model instances behave. See [the Python documentation](http://docs.python.org/2/reference/datamodel.html#customizing-attribute-access) for more information about descriptors.\n\nConstructor\n-----------\n\nThe constructor of the Property base class is defined as follows:\n\nclass Property(verbose_name=None, name=None, default=None, required=False, validator=None, choices=None, indexed=True)\n\n: The superclass of model property definitions.\n\n Arguments\n\n verbose_name\n : A user-friendly name of the property. This must always be the first argument to a property constructor. The `djangoforms` library uses this to make labels for form fields, and others can use it for a similar purpose.\n\n name\n : The storage name for the property, used in queries. This defaults to the attribute name used for the property. Because model classes have attributes other than properties (which cannot be used for properties), a property can use name to use a reserved attribute name as the property name in the datastore, and use a different name for the property attribute. See [Disallowed Property Names](/appengine/docs/legacy/standard/python/datastore/modelclass#Disallowed_Property_Names) for more information.\n\n default\n\n : A default value for the property. If the property value is never given a value, or is given a value of `None`, then the value is considered to be the default value.\n\n **Note:** Model class definitions are cached along with the rest of the application code. This includes caching default values for properties. Do not set a default in the model definition with data specific to the request (such as [users.get_current_user()](/appengine/docs/legacy/standard/python/refdocs/modules/google/appengine/api/users#get_current_user)). Instead, define an `__init__()` method for the [Model](/appengine/docs/legacy/standard/python/datastore/modelclass) class that initializes the property values.\n\n required\n\n : If `True`, the property cannot have a value of `None`. A model instance must initialize all required properties in its constructor so that the instance is not created with missing values. An attempt to create an instance without initializing a required property, or an attempt to assign `None` to a required property, raises a [BadValueError](/appengine/docs/legacy/standard/python/datastore/exceptions#BadValueError).\n\n A property that is both required and has a default value uses the default value if one is not given in the constructor. However, the property cannot be assigned a value of `None`, and there is no automatic way to restore the default value after another value has been assigned. You can always access the property's `default` attribute to get this value and assign it explicitly.\n\n validator\n : A function that should be called to validate the property's value when the value is assigned. The function takes the value as its only argument, and raises an exception if the value is invalid. The given validator is called after other validation has taken place, such as the check that a required property has a value. When a non-required property is not given a value, the validator is called with argument `None`.\n\n choices\n : A list of acceptable values for the property. If set, the property cannot be assigned a value not in the list. As with required and other validation, a model instance must initialize all properties with choices so that the instance is not created with invalid values. If choices is `None`, then all values that otherwise pass validation are acceptable.\n\n indexed\n\n : Whether this property should be included in the built-in and developer-defined [indexes](/appengine/docs/legacy/standard/python/datastore/indexes). If `False`, entities written to the datastore will never be returned by queries that sort or filter on this property, similar to [Blob](/appengine/docs/legacy/standard/python/datastore/typesandpropertyclasses#Blob) and [Text](/appengine/docs/legacy/standard/python/datastore/typesandpropertyclasses#Text) properties.\n\n **Note:** Every indexed property adds a small amount of overhead, CPU cost, and latency to `put()` and `delete()` calls. If you'll never need to filter or sort on a property, consider using `indexed=False` to avoid that overhead. Be careful, though! If you decide later that you want the property indexed after all, changing it back to `indexed=True` will only affect writes from that point onward. Entities that were originally written with `indexed=False` will not be re-indexed.\n\nClass Attributes\n----------------\n\nSubclasses of the Property class define the following class attribute:\n\n`data_type`\n: The Python data type or class the property accepts as a Python-native value.\n\nInstance Methods\n----------------\n\nInstances of Property classes have the following methods:\n\ndefault_value()\n\n: Returns the default value for the property. The base implementation uses the value of the default argument passed to the constructor. A property class could override this to provide special default value behavior, such as [DateTimeProperty](/appengine/docs/legacy/standard/python/datastore/typesandpropertyclasses#DateTimeProperty)'s auto-now feature.\n\nvalidate(value)\n\n: The complete validation routine for the property. If value is valid, it returns the value, either unchanged or adapted to the required type. Otherwise it raises an appropriate exception.\n\n The base implementation checks that value is not `None` if required (the required argument to the base Property constructor), the value is one of the valid choices if the property was configured with choices (the choices argument), and the value passes the custom validator if any (the validator argument).\n\n The validation routine is called when a model using the property type is instantiated (with default or initialized values), and when a property of the type is assigned a value. The routine should not have side effects.\n\nempty(value)\n\n: Returns `True` if value is considered an empty value for this property type. The base implementation is equivalent to `not value`, which is sufficient for most types. Other types, like a Boolean type, can override this method with a more appropriate test.\n\nget_value_for_datastore(model_instance)\n\n: Returns the value that ought to be stored in the datastore for this property in the given model instance. The base implementation simply returns the Python-native value of the property in the model instance. A property class can override this to use a different data type for the datastore than for the model instance, or to perform other data conversion just prior to storing the model instance.\n\nmake_value_from_datastore(value)\n\n: Returns the Python-native representation for the given value from the datastore. The base implementation simply returns the value. A property class can override this to use a different data type for the model instance than for the datastore.\n\nmake_value_from_datastore_index_value(value)\n\n: Returns the Python-native representation for the given value from the datastore index. The base implementation simply returns the value. A property class can override this to use a different data type for the model instance than for the datastore."]]