English ▼
Skip to page content Skip to main navigation
e.g. "templates" or "datastore"

# NDB Model Class

#### Experimental!

NDB is an experimental, innovative, and rapidly changing new feature for App Engine. Unfortunately, being on the bleeding edge means that we may make backwards-incompatible changes to NDB. We will inform the community when this feature is no longer experimental.

A class that inherits from the `Model` class represents a 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.

- Introduction
- Constructor
- Class Methods

- allocate_ids()
- allocate_ids_async()
- get_by_id()
- get_by_id_async()
- get_or_insert()
- get_or_insert_async()
- query()

- Instance Methods

- populate()
- put()
- put_async()

- Instance Data

- key

- Hook Methods

- _pre_allocated_ids_hook
- _post_allocate_ids_hook
- _pre_delete_hook
- _post_delete_hook
- _pre_get_hook
- _post_get_hook
- _pre_put_hook
- _post_put_hook

## Introduction

A class 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, simple 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).

## Constructor

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
  Key instance for this model. If the `key` parameter is used, `id` and `parent` must be `None` (the default).
id
  Key id for this model. If `id` is used, key must be `None` (the default).
parent
  Key instance for the parent model or `None` for a top-level one. If `parent` 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", or "parent". 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".

## Class Methods

allocate_ids(size=None, max=None, parent=None)

  Allocates a range of key IDs for this model class.

  Arguments:

  size
    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.

  Returns a tuple with (start, end) for the allocated range, inclusive.

  An application cannot call `allocate_ids()` in a transaction.

allocate_ids_async(size=None, max=None, parent=None)

  Asynchronous version of allocate_ids.

  Returns a `Future` object whose result is a tuple with (start, end) for the allocated range, inclusive.

get_by_id(id, parent=None)
  Returns an entity by ID. This is really just a shorthand for `Key(cls, id).get()`.

  Arguments:

  id
    A string or integer key ID.
  parent
    Parent key of the model to get.

  Returns a model instance or `None` if not found.

get_by_id_async(id, parent=None)
  Asynchronous version of get_by_id.

  Returns a `Future` object whose result is a model instance or `None` if not found.

get_or_insert(key_name, parent=None, **constructor_args)
  Transactionally retrieves an existing entity or creates a new one.

  Arguments:

  key_name
    A Key name to retrieve or create.
  parent
    Parent entity key, if any.

  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.

get_or_insert_async(key_name, parent=None, **constructor_args)

  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.

query(ancestor=None, app=None, namespace=None, filters=None, **q_options)
  Create a `Query` object for this class as described in Queries.

  Keyword arguments are passed to the Query constructor. If positional arguments are given, they are used to apply an initial filter.

  Returns a `Query` object.

## Instance Methods

populate(**constructor_options)

  Sets values of the entity's properties. Its keyword arguments automaticaly recognize property names in the same way that the constructor does.

put()

  Writes the entity's data to the Datastore. Returns the entity's Key.

put_async()

  Asynchronously writes the entity's data to the Datastore. Returns a `Future` object. The `Future` object's result will be the entity's Key.

## Instance Data

key
  Special property to store the Model key.

## Hook Methods

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.

@classmethod
_pre_allocate_ids_hook(cls, size, max, parent)
  Hook that runs before `allocate_ids()`
@classmethod
_post_allocate_ids_hook(cls, size, max, parent, future)
  Hook that runs after `allocate_ids()`
@classmethod
_pre_delete_hook(cls, key)
  Hook that runs before `delete()`
@classmethod
_post_delete_hook(cls, key, future)
  Hook that runs after `delete()`
@classmethod
_pre_get_hook(cls, key)
  Hook that runs before `Key.get()` when getting an entity of this model.
@classmethod
_post_get_hook(cls, key, future)
  Hook that runs after `Key.get()` when getting an entity of this model.
_pre_put_hook(self)
  Hook that runs before `put()`
_post_put_hook(self, future)
  Hook that runs after `put()`