Stay organized with collections Save and categorize content based on your preferences.
This page describes how to use the legacy bundled services and APIs. This API can only run in first-generation runtimes in the App Engine standard environment. If you are updating to the App Engine Python 3 runtime, refer to the migration guide to learn about your migration options for legacy bundled services.A class that inherits from the Model
class represents the structure of entities stored in the Datastore. Applications define model classes to indicate the structure of their entities, then instantiate those model classes to create entities. All model classes must inherit (directly or indirectly) from Model.
This page has API reference documentation. For an overview, please see NDB Entities and Keys.
IntroductionA class that inherits from Model
describes Datastore entities.
All model classes must inherit (directly or indirectly) from Model
. Straightforward assignments in the model class definition can be used to declare the model's structure:
from google.appengine.ext import ndb class Person(ndb.Model): name = ndb.StringProperty() age = ndb.IntegerProperty()
We can now create a Person entity and write it to the Datastore:
p = Person(name='Arthur Dent', age=42) k = p.put()
The return value from put()
is a Key, which can be used to retrieve the same entity later:
p2 = k.get() p2 == p # Returns True
To update an entity, simply change its attributes and write it back (note that this doesn't change the key):
p2.name = 'Arthur Philip Dent' p2.put()
We can also delete an entity (by using the key):
k.delete()
The property definitions in the class body tell the system the names and the types of the fields to be stored in the Datastore, whether they must be indexed, their default value, and more. Many different Property types exist.
The kind is normally equal to the class name (exclusive of the module name or any other parent scope). To override the kind (useful for schema changes), define a class method named _get_kind()
, as follows:
class MyModel(ndb.Model): @classmethod def _get_kind(cls): return 'AnotherKind'
An application should not define two model classes with the same kind, even if they live in different modules. An application's kinds are considered a global "namespace".
Model
subclasses may define pre-call and post-call hooks for most operations (get, put, delete, allocate_ids).
An application won't normally call Model()
, but is likely to call the constructor of a class that inherits from Model
. This creates a new instance of this model, also known as an entity.
The newly-created entity isn't automatically written to the Datastore. To make that happen, it must be written to the Datastore using an explicit call to put()
.
Arguments:
Model
subclasses support these keyword arguments:
key
parameter is used, id
and parent
must be None
(the default).
id
is used, key must be None
(the default).
None
for a top-level one. If parent
is used, key
must be None
.
None
(default) to use the current namespace. If namespace
is used, key
must be None
.
An application can also use keyword arguments mapping to the model's properties. For example, the following works:
class Person(ndb.Model): name = StringProperty() age = IntegerProperty() p = Person(name='Arthur Dent', age=42)
You cannot easily define a property named "key", "id", "parent", or "namespace". If you pass, for example, key="foo"
in a constructor or populate()
call, it sets the entity's key, not a property attribute named "key".
Note: If you override the constructor in a Model subclass, beware that the constructor is also called implicitly in some cases, and be sure that you support those calls. When an entity is read from the Datastore, an empty entity is first created by calling the constructor without arguments, after which the key and property values are set one by one. When get_or_insert()
or get_or_insert_async()
creates a new instance, it passes **constructor_args to the constructor, and sets the key afterwards.
Allocates a range of key IDs for this model class.
Arguments
size
or max
can be specified, not both.
size
or max
can be specified, not both.
Returns a tuple with (start, end) for the allocated range, inclusive.
An application cannot call allocate_ids()
in a transaction.
Asynchronous version of allocate_ids.
Returns a Future
object whose result is a tuple with (start, end) for the allocated range, inclusive.
Key(cls, id).get()
.
Arguments
Returns a model instance or None
if not found.
Returns a Future
object whose result is a model instance or None
if not found.
Arguments
This function also takes 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.
Returns existing instance of Model
class with the specified key name and parent or a new one that has just been created.
This function uses a transaction. If the code that calls this function is already in a transaction, this function attempts to re-use the existing transaction. If this function's entity group is incompatible with the existing transaction, this can cause an error.
This is the asynchronous version of get_or_insert.
It returns a Future
object whose result is an existing instance of Model
class with the specified key name and parent or a new one that has just been created.
Creates a Query
object for this class as described in Queries.
The keyword argument distinct
is shorthand for group_by = projection. All other keyword arguments are passed to the Query constructor.
If positional arguments are given, they are used to set up initial filters.
Returns a Query
object.
Sets values of the entity's properties. Its keyword arguments automatically recognize property names in the same way that the constructor does.
Writes the entity's data to the Datastore. Returns the entity's Key.
Arguments
Asynchronously writes the entity's data to the Datastore. Returns a Future
object. The Future
object's result will be the entity's Key.
Arguments
Returns a dict
containing the model's property values. Property values for StructuredProperty
and LocalStructuredProperty
are recursively converted into dictionaries.
Arguments:
Note: If a property value is a mutable object (e.g. a list representing a repeated property, or a dict or list stored in a JsonProperty
), unless the value is explicitly converted (e.g. in the case of a StructuredProperty
), the same object is returned in the dict that is stored in the entity. In such cases, mutating the dictionary will mutate the entity, and vice versa.
An application's subclass of Model
can define one or more of these methods as pre- or post- operation "hook" methods. E.g., to run some code before each "get", define the model subclass' _pre_get_hook()
method. For advice on writing hook functions, see Model Hooks.
allocate_ids()
allocate_ids()
delete()
delete()
Key.get()
when getting an entity of this model.
Key.get()
when getting an entity of this model.
put()
put()
You can use these methods to inspect the properties and configuration of a given model. This is useful if you're writing a library or function that accepts multiple types of models.
Lookup by kindEvery model has a kind that is usually the same as the class name unless overridden. You can use the kind to find the associated model class by using _lookup_model
.
class Animal(ndb.Model): type = ndb.StringProperty() print Animal._get_kind() # 'Animal' print ndb.Model._lookup_model('Animal') # class Animal
Note that _lookup_model
only works for model classes that have already been imported by the application.
You can get a list of all properties associated with a model using _properties
.
class User(ndb.Model): name = ndb.StringProperty() email = ndb.StringProperty() print User._properties # {'email': StringProperty('email'), 'name': StringProperty('name')}
_properties
also works for Expando instances.
class Example(ndb.Expando): pass e = Example() e.foo = 1 e.bar = 'blah' e.tags = ['exp', 'and', 'oh'] print e._properties # {'foo': GenericProperty('foo'), 'bar': GenericProperty('bar'), # 'tags': GenericProperty('tags', repeated=True)}
Property instances can be introspected. The options provided to the constructor are available as _
-prefixed properties.
print User._properties['email']._name # 'email' print User._properties['email']._required # False print User._properties['email']._default # None print User._properties['email']._choices # None print User._properties['email']._compressed # False print User._properties['email']._indexed # True print User._properties['email']._compressed # False print User._properties['email']._repeated # False print User._properties['email']._verbose_name # None print isinstance(User._properties['email'], ndb.StringProperty) # TrueMethod Aliases
Every method in the Model
class has a _
-prefixed alias. For example, _put()
is equivalent to put()
. This means that you can have properties with names that conflict with method names provided you always use the _
-prefixed methods. However, note that you can not specify any properties named key
, parent
, or id
in the constructor.
class MyModel(ndb.Model): put = ndb.StringProperty() query = ndb.StringProperty() key = ndb.StringProperty() entity = MyModel() entity.put = '1' entity.query = '2' entity.key = '3' entity._put() print entity # MyModel(key=Key('MyModel', ...), put=u'1', query=u'2', key=u'3') print MyModel._query().fetch() # same as above.
If you are creating third-party libraries that interact with arbitrary models, using the _
-prefixed methods is recommended.
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 2025-08-07 UTC.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Hard to understand","hardToUnderstand","thumb-down"],["Incorrect information or sample code","incorrectInformationOrSampleCode","thumb-down"],["Missing the information/samples I need","missingTheInformationSamplesINeed","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-08-07 UTC."],[[["This documentation explains the use of the `Model` class for defining and interacting with entities in the Datastore, which is part of the App Engine legacy bundled services."],["Model classes, which inherit from `ndb.Model`, are used to define the structure of Datastore entities, with properties specifying the names and types of the stored fields."],["Entities are created by instantiating model classes, and they are written to the Datastore using the `put()` method, which returns a Key for later retrieval."],["The `get_or_insert()` and `get_or_insert_async()` class methods can be used to retrieve an existing entity or create a new one transactionally, using the key name."],["Model subclasses can define hook methods (e.g., `_pre_get_hook`, `_post_put_hook`) to run custom code before or after certain operations, offering flexible control over entity interactions."]]],[]]
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4