Python 2.7 已达到支持终止期限,并将于 2026 年 1 月 31 日
弃用。弃用后,您将无法部署 Python 2.7 应用,即使您的组织之前曾使用组织政策重新启用旧版运行时的部署也是如此。现有的 Python 2.7 应用在
弃用日期之后将继续运行并接收流量。我们建议您
迁移到最新支持的 Python 版本。
Property 类
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
注意:强烈建议构建新应用的开发者使用 NDB 客户端库,它与 DB 客户端库相比具有多项优势,例如可通过 Memcache API 进行自动实体缓存。如果您当前使用的是较早的 DB 客户端库,请参阅 DB 到 NDB 的迁移指南
Property 类是数据模型的属性定义的父类。Property 类定义了属性值的类型、值的验证方式以及值在数据存储区中的存储方式。
Property
由 google.appengine.ext.db
模块提供。
简介
属性类描述了模型属性的值类型、默认值、验证逻辑和其他功能。每个属性类都是 Property 类的子类。数据存储区 API 包含每个数据存储区值类型的属性类,以及提供除数据存储区类型以外的其他功能的多个其他属性类。请参阅 Types 和 Property 类。
属性类可接受来自传递给构造函数的参数的配置。基类构造函数支持所有属性类中通常都支持的多个参数,包括数据存储区 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
- 属性的存储名称,可在查询中使用。这默认为用于属性的属性名称。由于模型类具有属性 (property) 以外的特性(attribute)(无法用于属性),因此属性可以使用 name 将保留的特性名称用作数据存储区中的属性名称,并且给属性特性指定一个不同的名称。如需了解详情,请参阅禁用的属性名称。
- 默认
-
属性的默认值。如果属性值从未指定过值或指定的值为 None
,则该属性值会视为默认值。
注意:模型类定义随应用代码的其余部分一起缓存。其中包括属性的缓存默认值。请勿使用特定于请求的数据(例如 users.get_current_user()
)在模型定义中设置 default。相反,请定义 Model 类的 __init__()
方法,可初始化属性值。
- required
-
如果为 True
,则属性值不能为 None
。模型实例必须通过其构造函数初始化所有必需的属性,这样创建实例时才不会缺少值。在没有初始化必需属性的情况下创建实例的尝试,或将 None
分配给必需属性的尝试,都会引发 BadValueError。
如果构造函数中不提供必需且具有默认值的属性,则该属性会使用默认值。但是,不能为该属性分配 None
值,也不能在分配了其他值后自动恢复默认值。您始终可以访问该属性的 default
特性来明确获取并分配此值。
- 验证器
- 分配属性值时为验证该值而应该调用的函数。该函数把该属性值作为其唯一参数,如果该值无效,则会引发异常。执行其他验证(例如,检查必需的属性是否具有一个值)后,会调用指定的验证程序。如果未给非必需属性指定值,则使用参数
None
调用验证程序。
- choices
- 可接受的属性值的列表。如果设置了该参数,则不能给属性分配该列表以外的其他值。与 required 和其他验证一样,模型实例必须初始化选择的所有属性,这样才不会使用无效值创建实例。如果 choices 为
None
,则所有以其他方式通过验证的值都是可接受的。
- indexed
-
不论开发者定义的内置索引中是否应该包含此属性。如果为 False
,则对此属性(类似于 Blob 和 Text 属性)进行排序或过滤的查询绝对不会返回写入到数据存储区的实体。
注意:每个编入索引的属性都会增加少量开销、CPU 费用,并延长对 put()
和 delete()
调用的时间。如果您根本无需对属性过滤或排序,请考虑使用 indexed=False
以避免这类开销。尽管如此,仍请务必小心谨慎!如果您稍后确定需要将该属性编入索引,则将它重新更改为 indexed=True
时,仅会影响从该点向前的写入内容。最初使用 indexed=False
写入的实体都不会重新编入索引。
类属性
Property 类的子类定义以下类属性:
data_type
- 属性接受作为 Python 自有值的 Python 数据类型或类。
实例方法
Property 类实例具有以下方法:
- default_value()
-
返回属性的默认值。基本实现方案使用传递给构造函数 default 参数的值。属性类可以替换该参数,以提供特殊默认值行为,如 DateTimeProperty 的 auto-now 功能。
- validate(value)
-
属性的完整验证程序。如果 value 有效,则会返回该值(保持不变或根据必需的类型进行了改变)。否则,便会引发相应的异常。
基本实现方案会检查 value 是否为 None
(如果需要,基本 Property 构造函数的 required 参数),检查 value 是否为有效选择之一(如果该属性使用 choices 配置,choices 参数)以及检查 value 是否通过自定义验证程序(如果有,validator 参数)。
当使用默认值或初始化值实例化使用该属性类型的模型时,以及为该类型的属性分配值时,会调用该验证例程。该例程不应该有副作用。
- empty(value)
-
如果 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 原生表示法。基本实现方案只返回该值。属性类可以将其替换,以便模型实例能够使用与数据存储区不同的其他数据类型。
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):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"]],["最后更新时间 (UTC):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."]]