Python 2.7 已終止支援,並將於 2026 年 1 月 31 日
淘汰。淘汰後,您將無法部署 Python 2.7 應用程式,即使貴機構先前曾使用機構政策重新啟用舊版執行階段的部署作業,也無法部署。現有的 Python 2.7 應用程式在
淘汰日期過後,仍會繼續執行並接收流量。建議您
改用系統支援的最新 Python 版本。
Property 類別
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
附註:我們強烈建議建構新應用程式的開發人員使用 NDB 用戶端程式庫,因為 NDB 用戶端程式庫與本用戶端程式庫相較之下有幾個優點,例如能透過 Memcache API 自動將實體加入快取。如果您目前使用的是舊版的 DB 用戶端程式庫,請參閱從 DB 至 NDB 的遷移指南。
Property 類別是資料模型屬性定義的父類別。Property 類別可定義屬性值的類型、屬性值的驗證方式,以及屬性值儲存在資料儲存庫中的方式。
Property
由 google.appengine.ext.db
模組提供。
簡介
屬性類別說明 Model 屬性的值類型、預設值、驗證邏輯及其他功能。每個屬性類別都是 Property 類別的子類別。資料儲存庫 API 包含各個資料儲存庫值類型的屬性類別,以及在資料儲存庫類型之上提供額外功能的其他屬性類別。請參閱「類型和 Property 類別」。
屬性類別可接受透過引數傳送給建構函式的設定。基本類別建構函式支援所有屬性類別通常都會支援的多個引數,包括資料儲存庫 API 中提供的所有引數。這些設定可包含預設值 (無論是否需要為明確值)、可接受的值清單,以及自訂驗證邏輯。如需更多關於設定屬性的資訊,請參閱特定屬性類型的說明文件。
屬性類別可定義資料儲存庫屬性的模型。它不包含模型執行個體的屬性值。Property 類別的執行個體屬於 Model 類別,而非該類別的執行個體。就 Python 而言,屬性 (property) 類別執行個體為自訂 Model 執行個體屬性 (attribute) 行為的「描述元」。如要進一步瞭解描述元的相關資訊,請參閱 Python 說明文件。
建構函式
Property 基本類別的建構函式定義如下:
- class Property(verbose_name=None, name=None, default=None, required=False, validator=None, choices=None, indexed=True)
-
模型屬性定義的父類別。
引數
- verbose_name
- 屬性的使用者友善名稱。規定必須為屬性建構函式的第一個引數。
djangoforms
程式庫會使用這個方法為表單欄位建立標籤,其他人也可以用於類似用途。
- name
- 屬性的儲存名稱,用於查詢。預設為 property (屬性) 使用的 attribute (屬性) 名稱。由於模型類別除了屬性 (無法用於屬性) 之外還有其他屬性,因此屬性可使用 name 將保留的屬性名稱用於資料儲存庫中的屬性名稱,並為屬性屬性使用不同的名稱。詳情請參閱「不允許使用的屬性名稱」。
- 預設
-
屬性預設值。如果屬性值從未指定任何值,或指定的值為 None
,則系統會將該值視為預設值。
注意:Model 類別定義會與其他應用程式的程式碼一併快取。這包括快取屬性預設值。請勿在模型定義中設定預設值,並使用特定要求的資料 (例如 users.get_current_user()
)。相反地,請針對 Model 類別定義 __init__()
方法,以便初始化屬性值。
- 必填
-
如果是 True
,則屬性不得具有 None
的值。模型執行個體必須將其建構函式中的所有必要屬性初始化,如此才不會建立遺失屬性值的執行個體。嘗試建立執行個體而沒有初始化必要屬性,或嘗試將 None
指派給必要屬性,將會發出 BadValueError。
如果沒有在建構函式中針對具有預設值的必要屬性指定其值,則會使用預設值。不過,屬性無法指派 None
值,且在指派其他值後,無法自動還原預設值。您隨時可以存取屬性的 default
屬性,取得這個值並明確指派。
- 驗證器
- 在指派值時,應呼叫的函式,用於驗證屬性值。這個函式會將屬性值作為唯一的引數;如果該值無效,就會發出例外狀況。在完成其他驗證 (例如檢查必要屬性具有屬性值) 後才會呼叫指定的驗證工具。如果非必要屬性未指定值,系統會使用引數
None
呼叫驗證工具。
- choices
- 屬性可接受的值清單。如有設定,則無法為屬性指派不在清單中的值。與required和其他驗證一樣,模型執行個體必須使用選項初始化所有屬性,以免使用無效值建立執行個體。如果 choices 為
None
,則接受所有值,否則會接受通過驗證的值。
- 已編入索引
-
指定這個屬性是否應包含在由開發人員定義的內建索引。如果為 False
,則排序或篩選這個屬性的查詢就絕不會傳回寫入到資料儲存庫的實體,這點跟 Blob 和 Text 屬性類似。
注意:每個已建立索引的屬性都會增加少量負擔與 CPU 成本,並造成 put()
和 delete()
呼叫延遲。如果您絕不會需要篩選或排序某個屬性,建議您使用 indexed=False
避免產生額外負擔。但請千萬小心!如果您之後決定要將屬性編入索引,將屬性變更回 indexed=True
只會影響從該時間點起的寫入作業。原本使用 indexed=False
編寫的實體不會重新索引。
類別屬性
Property 類別的子類別會定義下列類別屬性 (attribute):
data_type
- 屬性接受的 Python 資料類型或類別,做為 Python 原生值。
執行個體方法
Property 類別的執行個體方法如下:
- default_value()
-
傳回屬性的預設值。基本實作會採用傳送到建構函式的 default 引數值。屬性類別可以覆寫這個值,提供特殊的預設值行為,例如 DateTimeProperty 的自動現在功能。
- validate(value)
-
屬性的完整驗證常式。如果 value 為有效值,則會以原封不動方式傳回這個值,或將其修改為必要類型傳回。如果不是,會發出適用的例外狀況。
基礎實作會檢查 value 是否為 None
(如果需要,則為基礎屬性建構函式的 required 引數),如果屬性已使用選項進行設定,則值為有效選項之一 (choices 引數),且值會傳送至自訂驗證器 (如果有) (validator 引數)。
(使用預設或初始化的值) 實例化使用屬性類型的模型時,以及為類型的屬性指派值時,會呼叫這個驗證常式。這個常式不應帶來任何副作用。
- empty(value)
-
如果這個屬性類型的值視為空白值,則傳回 True
。基礎實作方式等同於 not value
,可滿足大多數類型的需求。布林值等其他類型則可使用更適當的測試來覆寫這個方法。
- get_value_for_datastore(model_instance)
-
針對指定模型執行個體中的這個屬性,傳回應儲存在資料儲存庫中的值。基本實作會針對模型執行個體中的屬性,僅傳回 Python 原生值。屬性類別可覆寫這個設定,為資料儲存庫使用不同於模型執行個體所用的資料類型,或在儲存模型執行個體前執行其他資料轉換。
- make_value_from_datastore(value)
-
從資料儲存庫傳回指定值的 Python 原生表示法。基本實作僅會傳回該值。屬性類別可覆寫這個設定,為模型執行個體使用不同於資料儲存庫所用的資料類型。
- make_value_from_datastore_index_value(value)
-
從資料儲存庫索引中傳回指定值的 Python 原生表示法。基本實作僅會傳回該值。屬性類別可覆寫這個設定,為模型執行個體使用不同於資料儲存庫所用的資料類型。
除非另有註明,否則本頁面中的內容是採用創用 CC 姓名標示 4.0 授權,程式碼範例則為阿帕契 2.0 授權。詳情請參閱《Google Developers 網站政策》。Java 是 Oracle 和/或其關聯企業的註冊商標。
上次更新時間:2025-09-04 (世界標準時間)。
[[["容易理解","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 (世界標準時間)。"],[[["\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."]]