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 クラスのサブクラスです。Datastore API には、データストア値の各型に対応するプロパティ クラスと、データストアの型に加えて追加機能を提供するその他のクラスが含まれています。詳細については、型とプロパティ クラスをご覧ください。
プロパティ クラスは、コンストラクタに渡された引数から設定を受け取ることができます。ベースクラスのコンストラクタは、すべてのプロパティ クラスで通常サポートされる複数の引数をサポートします。これには、Datastore API で提供されるすべての引数が含まれます。このような設定には、デフォルト値、明示的な値が必要かどうか、有効な値のリスト、カスタム検証ロジックを含めることができます。特定のプロパティの詳しい設定方法については、そのプロパティ型のドキュメントをご覧ください。
プロパティ クラスでは、データストア プロパティのモデルを定義します。モデル インスタンスのプロパティ値は含まれていません。Property クラスのインスタンスは、そのクラスのインスタンスではなく、Model クラスに属しています。Python の用語で言うと、プロパティ クラス インスタンスは Model インスタンスの属性の動作をカスタマイズする「記述子」です。記述子の詳細については、Python のドキュメントをご覧ください。
コンストラクタ
Property ベースクラスのコンストラクタは、次のように定義されています。
- class Property(verbose_name=None, name=None, default=None, required=False, validator=None, choices=None, indexed=True)
-
モデルのプロパティ定義のスーパークラス。
引数
- verbose_name
- プロパティのわかりやすい名前。これは、常にプロパティ コンストラクタの最初の引数である必要があります。
djangoforms
ライブラリでは、これを使用してフォーム フィールドのラベルを作成します。他のライブラリでも同様の目的でこれを使用できます。
- name
- クエリに使用するプロパティのストレージ名。デフォルト値は、プロパティに使用される属性名です。モデルクラスにはプロパティ以外の属性(プロパティに使用できないもの)があるため、プロパティで name を使用することにより、予約された属性名をデータストア内のプロパティ名として使用し、プロパティ属性には別の名前を使用できます。詳細については、使用できないプロパティ名をご覧ください。
- default
-
プロパティのデフォルト値。プロパティに値が指定されないか、値に None
が指定された場合は、この値がデフォルト値とみなされます。
注: Model クラスの定義は、アプリケーション コードの他の部分とともにキャッシュに保存されます。これには、プロパティのデフォルト値のキャッシュも含まれます。モデル定義の default にリクエスト固有のデータ(users.get_current_user()
など)を指定しないでください。代わりに、プロパティ値を初期化する Model クラスの __init__()
メソッドを定義してください。
- required
-
True
の場合は、プロパティに値 None
を指定できません。モデル インスタンスでは、値がない状態でインスタンスが作成されないように、すべての必須プロパティをコンストラクタで初期化する必要があります。必須プロパティを初期化せずにインスタンスを作成しようとする、または必須プロパティに None
を割り当てようとすると、BadValueError が発生します。
必須であると同時にデフォルト値を持つプロパティでは、コンストラクタで値が指定されない場合にデフォルト値が使用されます。ただし、プロパティに値 None
を割り当てることはできません。また、別の値を割り当てた後でデフォルト値に自動的に戻す方法はありません。いつでもプロパティの default
属性にアクセスしてこの値を取得し、それを明示的に割り当てることができます。
- validator
- プロパティの値を割り当てたときに値を検証するために呼び出す必要がある関数。この関数は、唯一の引数として値を取り、値が無効な場合は例外を生成します。指定された検証ツールは、必須プロパティに値があるかどうかのチェックなど、他の検証が行われた後で呼び出されます。必須でないプロパティに値が指定されなかった場合は、引数に
None
を指定して検証ツールが呼び出されます。
- choices
- プロパティに指定できる値のリスト。設定されている場合は、このリストにない値をプロパティに割り当てることができません。required やその他の検証と同様に、モデル インスタンスでは、無効な値を使用してインスタンスが作成されないように、choices を使用してすべてのプロパティを初期化する必要があります。choices が
None
の場合は、他の検証に成功したすべての値が許容されます。
- indexed
-
組み込みまたはデベロッパー定義のインデックスにこのプロパティを含めるかどうか。False
が指定されてデータストアに書き込まれたエンティティは、Blob プロパティや Text プロパティと同じように、このプロパティで並べ替えまたはフィルタリングするクエリでは返されません。
注: プロパティをインデックスに登録すると、put()
と delete()
の呼び出し時に少量のオーバーヘッド、CPU コスト、レイテンシが追加されます。このプロパティでフィルタリングや並べ替えを行う必要がない場合は、indexed=False
を使用してオーバーヘッドを回避することを検討してください。ただし、注意事項があります。プロパティがインデックスに登録されるように、時間をおいて indexed=True
へ変更した場合、それ以降の書き込みにのみ反映されます。indexed=False
で書き込まれたエンティティは、インデックスに再登録されません。
クラス属性
Property クラスのサブクラスでは、次のクラス属性が定義されます。
data_type
- プロパティに Python ネイティブ値として指定できる Python データ型またはクラス。
インスタンス メソッド
Property クラスのインスタンスには、次のメソッドがあります。
- default_value()
-
プロパティのデフォルト値を返します。ベース実装では、コンストラクタに渡された default 引数の値が使用されます。プロパティ クラスでこれをオーバーライドして、特別なデフォルト値の動作(DateTimeProperty で自動的に現在日時を設定する機能など)を設定できます。
- validate(value)
-
プロパティの完全な検証ルーチン。value が有効な場合は、その値を変更せずに、または必要な型に変換してから返します。無効な場合は、該当する例外を生成します。
ベース実装では、必須の value(ベース Property コンストラクタへの required 引数)が None
でないこと、プロパティが選択肢(choices 引数)を使用して構成されている場合には値が有効な選択肢のいずれかであること、さらに、カスタム検証ツールがある(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 Developers サイトのポリシーをご覧ください。Java は 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."]]