Synchronously get the entity for this Key.
Return None if there is no such entity.
Return a Future whose result is the entity for this Key.
If no such entity exists, a Future is still returned, and the Future’s eventual return result be None.
Return the string or integer id in the last (kind, id) pair, if any.
ReturnsA string or integer id, or None if the key is incomplete.
Return the integer id in the last (kind, id) pair, if any.
ReturnsAn integer id, or None if the key has a string id or is incomplete.
Return the kind of the entity referenced.
This is the kind from the last (kind, id) pair.
Return the namespace.
Return a tuple of (kind, id) pairs.
Return a Key constructed from all but the last (kind, id) pairs.
If there is only one (kind, id) pair, return None.
Return the Reference object for this Key.
This is a entity_pb.Reference instance – a protocol buffer class used by the lower-level API to the datastore.
NOTE: The caller should not mutate the return value.
Return the root key. This is either self or the highest parent.
Return a serialized Reference object for this Key.
Return the string id in the last (kind, id) pair, if any.
ReturnsA string id, or None if the key has an integer id or is incomplete.
Return a url-safe string encoding this Key’s Reference.
This string is compatible with other APIs and languages and with the strings used to represent Keys in GQL and in the App Engine Admin Console.
Bases: object
Key used to identify a blob in Blobstore.
This object wraps a string that gets used internally by the Blobstore API to identify application blobs. The BlobKey corresponds to the entity name of the underlying BlobReference entity.
This class is exposed in the API in both google.appengine.ext.db and google.appengine.ext.blobstore.
Bases: object
A geographical point, specified by floating-point latitude and longitude coordinates. Often used to integrate with mapping sites like Google Maps. May also be used as ICBM coordinates.
This is the georss:point element. In XML output, the coordinates are provided as the lat and lon attributes. See: http://georss.org/
Serializes to ‘<lat>,<lon>’. Raises BadValueError if it’s passed an invalid serialized string, or if lat and lon are not valid floating points in the ranges [-90, 90] and [-180, 180], respectively.
Bases: google.appengine.api.datastore_errors.Error
May be raised by transaction functions when they want to roll back instead of committing. Note that any exception raised by a transaction function will cause a rollback. This is purely for convenience. See datastore.RunInTransaction for details.
Bases: google.appengine.ext.ndb.model._NotEqualMixin
Immutable object representing an index.
Whether this is an ancestor index, a bool.
The kind being indexed, a string.
A list of PropertyIndex objects giving the properties being indexed.
Bases: google.appengine.ext.ndb.model._NotEqualMixin
Immutable object representing and index and its state.
An Index object describing the index.
The index ID, an integer.
The index state, a string.
Possible values are ‘error’, ‘deleting’, ‘serving’ or ‘building’.
Bases: google.appengine.ext.ndb.model._NotEqualMixin
Immutable object representing a single property in an index.
The direction in the index for this property, ‘asc’ or ‘desc’.
The property name being indexed, a string.
Bases: google.appengine.datastore.datastore_rpc.AbstractAdapter
Conversions between ‘our’ Key and Model classes and protobufs.
This is needed to construct a Connection object, which in turn is needed to construct a Context object.
See the base class docstring for more info about the signatures.
Bases: object
A Base class signifying the presence of a _fix_up() method.
Bases: google.appengine.ext.ndb.model.Property
Special property to store the Model key.
Bases: type
Metaclass for Model.
This exists to fix up the properties – they need to know their name. This is accomplished by calling the class’s _fix_properties() method.
Bases: google.appengine.ext.ndb.model._NotEqualMixin
A class describing Cloud Datastore entities.
Model instances are usually called entities. All model classes inheriting from Model automatically have MetaModel as their metaclass, so that the properties are fixed up properly after the class once the class is defined.
Because of this, you cannot use the same Property object to describe multiple properties – you must create separate Property objects for each property. E.g. this does not work:
wrong_prop=StringProperty()classWrong(Model):wrong1=wrong_propwrong2=wrong_prop
The kind is normally equal to the class name (exclusive of the module name or any other parent scope). To override the kind, define a class method named _get_kind(), as follows:
classMyModel(Model):@classmethoddef_get_kind(cls):return'AnotherKind'
Allocates a range of key IDs for this model class.
Parameterssize – Number of IDs to allocate. Either size or max can be specified, not both.
max – Maximum ID to allocate. Either size or max can be specified, not both.
parent – Parent key for which the IDs will be allocated.
**ctx_options – Context options.
A tuple with (start, end) for the allocated range, inclusive.
Allocates a range of key IDs for this model class.
This is the asynchronous version of Model._allocate_ids().
Returns an instance of Model class by ID.
This is really just a shorthand for Key(cls, id, …).get().
Parametersid – A string or integer key ID.
parent – Optional parent key of the model to get.
namespace – Optional namespace.
app – Optional app ID.
**ctx_options – Context options.
A model instance or None if not found.
Returns an instance of Model class by ID (and app, namespace).
This is the asynchronous version of Model._get_by_id().
Transactionally retrieves an existing entity or creates a new one.
name: Key name to retrieve or create.
namespace – Optional namespace.
app – Optional app ID.
parent – Parent entity key, if any.
context_options – ContextOptions object (not keyword args!) or None.
**kwds – Keyword arguments to pass to the constructor of the model class if an instance for the specified key name does not already exist. If an instance with the supplied key_name and parent already exists, these arguments will be discarded.
Existing instance of Model class with the specified key name and parent or a new one that has just been created.
Transactionally retrieves an existing entity or creates a new one.
This is the asynchronous version of Model._get_or_insert().
Run a GQL query.
Return whether this entity has a complete key.
Special property to store the Model key.
Populate an instance from keyword arguments.
Each keyword argument will be used to set a corresponding property. Keywords must refer to valid property name. This is similar to passing keyword arguments to the Model constructor, except that no provisions for key, id or parent are made.
Write this entity to Cloud Datastore.
If the operation creates or completes a key, the entity’s key attribute is set to the new, complete key.
ReturnsThe key for the entity. This is always a complete key.
Write this entity to Cloud Datastore.
This is the asynchronous version of Model._put().
Create a Query object for this class.
Parametersdistinct – Optional bool, short hand for group_by = projection.
*args – Used to apply an initial filter
**kwds – are passed to the Query() constructor.
A Query object.
Return a dict containing the entity’s property values.
Parametersinclude – Optional set of property names to include, default all.
exclude – Optional set of property names to skip, default none. A name contained in both include and exclude is excluded.
Bases: google.appengine.ext.ndb.model.Model
Model subclass to support dynamic Property names and types.
See the module docstring for details.
Run a callback in a transaction.
Parameterscallback – A function or tasklet to be called.
**ctx_options – Transaction options.
retries=N: Retry up to N times (i.e. try up to N+1 times) propagation=<flag>: Determines how an existing transaction should be
propagated, where <flag> can be one of the following: TransactionOptions.NESTED: Start a nested transaction (this is the
default; but actual nested transactions are not yet implemented, so effectively you can only use this outside an existing transaction).
TransactionOptions.MANDATORY: A transaction must already be in progress. TransactionOptions.ALLOWED: If a transaction is in progress, join it. TransactionOptions.INDEPENDENT: Always start a new parallel transaction.
transactions, i.e. allow writing to up to 5 entity groups.
potentially allows for more throughput.
WARNING: Using anything other than NESTED for the propagation flag can have strange consequences. When using ALLOWED or MANDATORY, if an exception is raised, the transaction is likely not safe to commit. When using INDEPENDENT it is not generally safe to return values read to the caller (as they were not read in the caller’s transaction).
ReturnsWhatever callback() returns.
RaisesWhatever callback() raises; datastore_errors.TransactionFailedError
if the transaction failed.
Run a callback in a transaction.
This is the asynchronous version of transaction().
Return whether a transaction is currently active.
Fetches a sequence of keys.
Parameterskeys – A sequence of keys.
**ctx_options – Context options.
A list whose items are either a Model instance or None if the key wasn’t found.
Fetches a sequence of keys.
Parameterskeys – A sequence of keys.
**ctx_options – Context options.
A list of futures.
Stores a sequence of Model instances.
Parametersentities – A sequence of Model instances.
**ctx_options – Context options.
A list with the stored keys.
Stores a sequence of Model instances.
Parametersentities – A sequence of Model instances.
**ctx_options – Context options.
A list of futures.
Deletes a sequence of keys.
Parameterskeys – A sequence of keys.
**ctx_options – Context options.
A list whose items are all None, one per deleted key.
Deletes a sequence of keys.
Parameterskeys – A sequence of keys.
**ctx_options – Context options.
A list of futures.
Get a data structure representing the configured indexes.
Parameters**ctx_options – Context options.
ReturnsA list of Index objects.
Get a data structure representing the configured indexes.
Parameters**ctx_options – Context options.
ReturnsA future.
Create a new Connection object with the right adapter.
Optionally you can pass in a datastore_rpc.Configuration object.
Bases: google.appengine.ext.ndb.model.Property
A Property whose value is a byte string. It may be compressed.
Bases: google.appengine.ext.ndb.model.BlobProperty
A property whose value is any Json-encodable Python object.
Bases: google.appengine.ext.ndb.model.TextProperty
An indexed Property whose value is a text string of limited length.
Bases: google.appengine.ext.ndb.model.Property
A Property whose value is a Python float.
Note: int, long and bool are also allowed.
alias of InvalidPropertyError
Bases: google.appengine.ext.ndb.model._StructuredGetForDictMixin, google.appengine.ext.ndb.model.BlobProperty
Substructure that is serialized to an opaque blob.
This looks like StructuredProperty on the Python side, but is written like a BlobProperty in Cloud Datastore. It is not indexed and you cannot query for subproperties. On the other hand, the on-disk representation is more efficient and can be made even more efficient by passing compressed=True, which compresses the blob data using gzip.
Bases: google.appengine.ext.ndb.model.DateTimeProperty
A Property whose value is a time object.
Bases: google.appengine.ext.ndb.model.Property
A Property whose value is a User object.
Note: this exists for backwards compatibility with existing Cloud Datastore schemas only; we do not recommend storing User objects directly in Cloud Datastore, but instead recommend storing the user.user_id() value.
Bases: google.appengine.api.datastore_errors.Error
Raised when a property is not applicable to a given use.
For example, a property must exist and be indexed to be used in a query’s projection or group by clause.
Bases: google.appengine.api.datastore_errors.BadValueError
Raised when an implementation for a kind can’t be found.
Also raised when the Kind is not an 8-bit string.
Bases: google.appengine.ext.ndb.model.GenericProperty
A Property whose value is determined by a user-supplied function.
Computed properties cannot be set directly, but are instead generated by a function when required. They are useful to provide fields in Cloud Datastore that can be used for filtering or sorting without having to manually set the value in code - for example, sorting on the length of a BlobProperty, or using an equality filter to check if another field is not empty.
ComputedProperty can be declared as a regular property, passing a function as the first argument, or it can be used as a decorator for the function that does the calculation.
Example:
>>> class DatastoreFile(Model): ... name = StringProperty() ... name_lower = ComputedProperty(lambda self: self.name.lower()) ... ... data = BlobProperty() ... ... @ComputedProperty ... def size(self): ... return len(self.data) ... ... def _compute_hash(self): ... return hashlib.sha1(self.data).hexdigest() ... hash = ComputedProperty(_compute_hash, name='sha1')Bases: google.appengine.ext.ndb.model.Property
A Property whose value is a Key object.
Optional keyword argument: kind=<kind>, to require that keys assigned to this property always have the indicated kind. May be a string or a Model subclass.
Bases: google.appengine.ext.ndb.model.Property
A Property whose value is a Python bool.
Bases: google.appengine.ext.ndb.model.BlobProperty
A Property whose value is any picklable Python object.
Bases: google.appengine.ext.ndb.model.Property
A Property whose value is a Python int or long (or bool).
Bases: google.appengine.ext.ndb.model.ModelAttribute
A class describing a typed, persisted attribute of a Cloud Datastore entity.
Not to be confused with Python’s ‘property’ built-in.
This is just a base class; there are specific subclasses that describe Properties of various types (and GenericProperty which describes a dynamically typed Property).
All special Property attributes, even those considered ‘public’, have names starting with an underscore, because StructuredProperty uses the non-underscore attribute namespace to refer to nested Property names; this is essential for specifying queries on subproperties (see the module docstring).
The Property class and its predefined subclasses allow easy subclassing using composable (or stackable) validation and conversion APIs. These require some terminology definitions:
A ‘user value’ is a value such as would be set and accessed by the application code using standard attributes on the entity.
A ‘base value’ is a value such as would be serialized to and deserialized from Cloud Datastore.
The values stored in ent._values[name] and accessed by _store_value() and _retrieve_value() can be either user values or base values. To retrieve user values, use _get_user_value(). To retrieve base values, use _get_base_value(). In particular, _get_value() calls _get_user_value(), and _serialize() effectively calls _get_base_value().
To store a user value, just call _store_value(). To store a base value, wrap the value in a _BaseValue() and then call _store_value().
A Property subclass that wants to implement a specific transformation between user values and serialiazble values should implement two methods, _to_base_type() and _from_base_type(). These should NOT call their super() method; super calls are taken care of by _call_to_base_type() and _call_from_base_type(). This is what is meant by composable (or stackable) APIs.
The API supports ‘stacking’ classes with ever more sophisticated user<–>base conversions: the user–>base conversion goes from more sophisticated to less sophisticated, while the base–>user conversion goes from less sophisticated to more sophisticated. For example, see the relationship between BlobProperty, TextProperty and StringProperty.
In addition to _to_base_type() and _from_base_type(), the _validate() method is also a composable API.
The validation API distinguishes between ‘lax’ and ‘strict’ user values. The set of lax values is a superset of the set of strict values. The _validate() method takes a lax value and if necessary converts it to a strict value. This means that when setting the property value, lax values are accepted, while when getting the property value, only strict values will be returned. If no conversion is needed, _validate() may return None. If the argument is outside the set of accepted lax values, _validate() should raise an exception, preferably TypeError or datastore_errors.BadValueError.
Example/boilerplate:
‘Lax user value to strict user value.’ if not isinstance(value, <top type>):
raise TypeError(…) # Or datastore_errors.BadValueError(…).
‘(Strict) user value to base value.’ if isinstance(value, <user type>):
return <base type>(value)
‘base value to (strict) user value.’ if not isinstance(value, <base type>):
return <user type>(value)
Things that _validate(), _to_base_type() and _from_base_type() do not need to handle:
None: They will not be called with None (and if they return None, this means that the value does not need conversion).
Repeated values: The infrastructure (_get_user_value() and _get_base_value()) takes care of calling _from_base_type() or _to_base_type() for each list item in a repeated value.
Wrapping values in _BaseValue(): The wrapping and unwrapping is taken care of by the infrastructure that calls the composable APIs.
Comparisons: The comparison operations call _to_base_type() on their operand.
Distinguishing between user and base values: the infrastructure guarantees that _from_base_type() will be called with an (unwrapped) base value, and that _to_base_type() will be called with a user value.
Returning the original value: if any of these return None, the original value is kept. (Returning a differen value not equal to None will substitute the different value.)
Comparison operator for the ‘in’ comparison operator.
The Python ‘in’ operator cannot be overloaded in the way we want to, so we define a method. For example:
Employee.query(Employee.rank.IN([4,5,6]))
Note that the method is called ._IN() but may normally be invoked as .IN(); ._IN() is provided for the case you have a StructuredProperty with a model that has a Property named IN.
Bases: google.appengine.ext.ndb.model.DateTimeProperty
A Property whose value is a date object.
Bases: google.appengine.ext.ndb.model.BlobProperty
An unindexed Property whose value is a text string of unlimited length.
Bases: google.appengine.ext.ndb.model.Property
A Property whose value is a datetime object.
Note: Unlike Django, auto_now_add can be overridden by setting the value before writing the entity. And unlike classic db, auto_now does not supply a default value. Also unlike classic db, when the entity is written, the property values are updated to match what was written. Finally, beware that this also updates the value in the in-process cache, and that auto_now_add may interact weirdly with transaction retries (a retry of a property with auto_now_add set will reuse the value that was set on the first try).
Bases: google.appengine.ext.ndb.model.Property
A Property whose value can be (almost) any basic type.
This is mainly used for Expando and for orphans (values present in Cloud Datastore but not represented in the Model subclass) but can also be used explicitly for properties with dynamically-typed values.
This supports compressed=True, which is only effective for str values (not for unicode), and implies indexed=False.
Bases: google.appengine.api.datastore_errors.Error
Raised when getting a property value that’s not in the projection.
Bases: google.appengine.ext.ndb.model.Property
A Property whose value is a GeoPt.
Bases: google.appengine.ext.ndb.model.ReadonlyPropertyError
Raised when attempting to set a value to or delete a computed property.
Bases: google.appengine.ext.ndb.model.Property
A Property whose value is a BlobKey object.
Bases: google.appengine.api.datastore_errors.Error
Raised when attempting to set a property value that is read-only.
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2023-04-04 UTC.