Model Reference¶
Core model definitions for the Google Cloud Datastore ODM.
This module provides the base Model class, its metaclass, and validation
decorators required to define and interact with Datastore entities.
Model(**kwargs)
¶
Base ODM model for Google Cloud Datastore.
Responsibilities
- Property validation and memory storage
- Model-level and Field-level validation routing
- Datastore persistence, mapping, and hydration
- Lifecycle hook execution
Initialize a new model instance. Properties can be passed as keyword arguments.
Keyword arguments to explicitly set Datastore key components
keyidparent
Note
If your model has an actual property named after the aforementioned keywords, and yet you still need to use Datastore key components and/or routing metadata, prefix the related keyword arguments with an underscore:
_id_parent_project_database_namespace
Warning
key is reserved and prohibited from being used as a property name but if you have an actual Datastore
field called key you can still access it by using the alias feature.
e.g:
class User(Model):
user_key = StringProperty(name='key')
name = StringProperty()
age = IntegerProperty()
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs
|
Any
|
Property values and Datastore routing metadata. |
{}
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If a required property is missing. |
AttributeError
|
If an unknown property is provided. |
Examples:
# Create a model with an auto-generated ID
user = User(name="Alice", age=30)
# Create a model with an explicit string ID
user = User(id="alice-123", name="Alice")
items()
¶
Return a view of the model's property names and values.
to_dict(include=None, exclude=None)
¶
Return a shallow dictionary representation of the model properties.
Returns raw Python types (e.g., datetime, bytes, datastore.Key).
For a JSON-serialized string representation, use to_json().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include
|
list[str] | None
|
If provided, only include these Python property names. |
None
|
exclude
|
list[str] | None
|
If provided, exclude these Python property names. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: A dictionary mapping Python property names to their current values. |
to_json_dict(include=None, exclude=None)
¶
Internal helper to build a perfectly JSON-safe dictionary of primitives.
This prevents double-serialization bugs when structured properties embed other models that also call to_json().
to_json(include=None, exclude=None)
¶
Return a strict JSON string representation of the model.
Executes default serialization for complex properties (e.g., datetimes to ISO strings,
keys to urlsafe strings) and applies any custom @field_serializer hooks.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include
|
list[str] | None
|
If provided, only serialize these Python property names. |
None
|
exclude
|
list[str] | None
|
If provided, exclude these Python property names. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The JSON-encoded string. |
validate()
¶
Execute all model-level validators.
Property-level validation automatically occurs during standard assignment. This
method runs methods decorated with @model_validator to verify cross-property logic.
kind()
classmethod
¶
Return the Datastore kind associated with this model class.
get_schema(output_format='full')
classmethod
¶
Introspect the model's schema and property configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_format
|
Literal['full', 'properties', 'named_properties', 'property_names', 'property_aliases']
|
Determines the structure of the returned data. Defaults to |
'full'
|
Returns:
| Name | Type | Description |
|---|---|---|
Any |
Any
|
The schema representation. The return type varies based on the requested format: |
Any
|
|
|
Any
|
|
|
Any
|
|
|
Any
|
|
|
Any
|
|
allocate_ids(size, parent=None, project=None, database=None, namespace=None)
classmethod
¶
Allocate a batch of integer IDs for this model's kind.
Reserves a block of numeric IDs directly from the Datastore backend. This is useful for generating guaranteed-unique IDs before instantiating objects.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
size
|
int
|
The number of IDs to allocate. Must be > 0. |
required |
parent
|
Key | None
|
An optional ancestor key for the allocated IDs. |
None
|
project
|
str | None
|
An optional project override. |
None
|
database
|
str | None
|
An optional database override. |
None
|
namespace
|
str | None
|
An optional namespace override. |
None
|
Returns:
| Type | Description |
|---|---|
list[Key]
|
list[datastore.Key]: A list of fully resolved keys with allocated integer IDs. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the requested size is 0 or negative. |
allocate_key(parent=None)
¶
Explicitly allocate a complete datastore key for this specific instance.
Triggers a single RPC call to the Datastore to fetch an integer ID.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parent
|
Key | None
|
An optional ancestor key. |
None
|
Returns:
| Type | Description |
|---|---|
Key
|
datastore.Key: The newly allocated, fully resolved Key. |
client(project=None, database=None)
classmethod
¶
Retrieve the configured active Datastore client.
key_from_id(identifier, parent=None, project=None, database=None, namespace=None)
classmethod
¶
Construct a datastore Key for this model's kind.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
identifier
|
Any
|
The string or integer ID for the entity. |
required |
parent
|
Key | None
|
An optional ancestor key. |
None
|
project
|
str | None
|
An optional project override. |
None
|
database
|
str | None
|
An optional database override. |
None
|
namespace
|
str | None
|
An optional namespace override. |
None
|
Returns:
| Type | Description |
|---|---|
Key
|
datastore.Key: The constructed Key object. |
populate(**kwargs)
¶
Update multiple properties at once.
Triggers all descriptor and field validators during assignment.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs
|
Any
|
Property names and their new values. |
{}
|
Raises:
| Type | Description |
|---|---|
AttributeError
|
If an unknown property is provided. |
from_entity(entity, _is_projected=False)
classmethod
¶
Create a model instance from a raw datastore Entity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
entity
|
Entity | None
|
The retrieved Datastore entity. |
required |
_is_projected
|
bool
|
Internal flag marking if this was fetched via projection. |
False
|
Returns:
| Type | Description |
|---|---|
TModel | None
|
Model | None: A hydrated Python model instance, or None if no entity was provided. |
get(key)
classmethod
¶
Fetch an entity by its Datastore key and hydrate a model instance.
Executes the _pre_get_hook before fetching, and the _post_get_hook
after hydration (even if the entity was not found).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
Key
|
The Google Cloud Datastore Key to fetch. |
required |
Returns:
| Type | Description |
|---|---|
TModel | None
|
Model | None: The hydrated model instance, or None if not found. |
Examples:
get_by_id(identifier, parent=None)
classmethod
¶
Fetch an entity by its string or integer ID.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
identifier
|
Any
|
The string name or integer ID. |
required |
parent
|
Key | None
|
An optional ancestor key. |
None
|
Returns:
| Type | Description |
|---|---|
TModel | None
|
Model | None: The hydrated model instance, or None if not found. |
Examples:
query(project=None, database=None, namespace=None)
classmethod
¶
Create a Query object for this model's Datastore kind.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
project
|
str | None
|
An optional project override. |
None
|
database
|
str | None
|
An optional database override. |
None
|
namespace
|
str | None
|
An optional namespace override. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
Query |
Query[TModel]
|
An ODM Query object ready for filtering and fetching. |
Examples:
put(exclude_from_indexes=None)
¶
Persist the model instance to the Datastore.
Triggers model-level validation and runs the _pre_put_hook and _post_put_hook.
If the instance does not have a complete key, Datastore auto-assigns an ID natively.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
exclude_from_indexes
|
list[str] | None
|
An optional list of Python property names (or even raw datastore fields) to dynamically exclude from Datastore indexes for this specific write. |
None
|
Returns:
| Type | Description |
|---|---|
Key
|
datastore.Key: The fully resolved Datastore Key. |
delete()
¶
Delete the model instance from the Datastore.
Executes the _pre_delete_hook before deletion and _post_delete_hook after.
Raises:
| Type | Description |
|---|---|
ValueError
|
If the entity does not have a key. |
get_multi(keys)
classmethod
¶
Fetch multiple entities by their keys in a single RPC call.
Returns a list of model instances in the exact order of the provided keys.
Missing entities are represented as None in the returned list.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
keys
|
list[Key]
|
A list of Datastore keys to fetch. |
required |
Returns:
| Type | Description |
|---|---|
list[TModel | None]
|
list[Model | None]: Hydrated instances or None, preserving input order. |
put_multi(instances)
classmethod
¶
Persist multiple model instances in a single batch Datastore operation.
This is significantly faster and more cost-effective than calling .put()
in a loop. Hooks (_pre_put_hook, _post_put_hook) and validators are
triggered for each instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
instances
|
list[Model]
|
A list of unsaved or modified model instances. |
required |
Returns:
| Type | Description |
|---|---|
list[Key]
|
list[datastore.Key]: A list of keys corresponding to the saved entities. |
field_validator(field)
¶
Decorator used to mark a method as a field-level validator.
Field validators run automatically when
- an instance is created.
- a property is assigned.
Model.populate()is called.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
field
|
str
|
The name of the Python property this validates. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Callable |
Callable
|
A decorator for the specific validation method. |
Examples:
model_validator(func)
¶
Decorator used to mark a method as a model-level validator.
Model-level validators are executed when
Model.validate()is called explicitly.Model.put()orModel.put_multi()is called.
They are NOT executed during instantiation or property assignment.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Callable
|
The method to decorate. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Callable |
Callable
|
The decorated method. |
Examples: