English
Skip to page content Skip to main navigation

e.g. "templates" or "datastore"

# The Model Class

The Model class is the superclass for data model definitions.

`Model` is provided by the `google.appengine.ext.db` module.

- Introduction
- Model()
- Class methods:
  - Model.get()
  - Model.get_by_id()
  - Model.get_by_key_name()
  - Model.get_or_insert()
  - Model.all()
  - Model.gql()
  - Model.kind()
  - Model.properties()
- Instance methods:
  - key()
  - put()
  - delete()
  - is_saved()
  - parent()
  - parent_key()
  - to_xml()
- Disallowed Property Names

## Introduction

An application defines a data model by defining a class that subclasses Model. Properties of the model are defined using class attributes and Property class instances. For example:

    class Story(db.Model):
      title = db.StringProperty()
      body = db.TextProperty()
      created = db.DateTimeProperty(auto_now_add=True)

An application creates a new data entity by instantiating a subclass of the Model class. Properties of an entity can be assigned using attributes of the instance, or as keyword arguments to the constructor.

    s = Story()
    s.title = "The Three Little Pigs"

    s = Story(title="The Three Little Pigs")

The name of the model sub-class is used as the name of the datastore entity kind. The names of the attributes are used as the names of the corresponding properties on an entity. Model instance attributes whose names begin with an underscore (`_`) are ignored, so your application can use such attributes to store data on a model instance that isn't saved to the datastore.

The datastore and the model class API impose several restrictions on property names and model instance attributes. See Disallowed Property Names for a complete description.

A data entity can have an optional parent entity. Parent-child relationships form entity groups, which are used to control transactionality and data locality in the datastore. An application creates a parent-child relationship between two entities by passing the parent entity to the child entity's constructor, as the parent argument. For more information about parents and ancestors, see Keys and Entity Groups.

Every entity has a key, a unique identifier that represents the entity. An entity can have an optional key name, a string unique across entities of the given kind. The entity's kind and name can be used with the Key.from_path() and Model.get_by_key_name() methods to retrieve the entity. For more information about keys, see Keys and Entity Groups.

The method Model.get_or_insert() can be used to retrieve an entity that may not exist, creating it in the datastore if necessary:

    keyname = "some_key"
    s = Story.get_or_insert(keyname, title="The Three Little Pigs")

Note: A Model instance does not have a corresponding entity in the datastore until it is put() for the first time, either explicitly so or via Model.get_or_insert().

The Model class is provided by the `google.appengine.ext.db` package.

## Constructor

The constructor of the Model class is defined as follows:

class Model(parent=None, key_name=None, **kwds)

  The superclass for data model definitions.

  Arguments:

  parent
    The Model instance or Key instance for the entity that is the new entity's parent.
  key_name

    The name for the new entity. The name becomes part of the primary key. If `None`, a system-generated ID is used for the key.

    The value for key_name must not start with a number, and must not be of the form `__*__`. If your application uses user-submitted data as datastore entity key names (such as an email address), the application should sanitize the value first, such as by prefixing it with a known string like "key:", to meet these requirements.

    A `key_name` is stored as a Unicode string, with `str` values converted as ASCII text.

  **kwds
    Initial values for the instance's properties, as keyword arguments. Each name corresponds with an attribute defined on the Model class.

## Class Methods

The Model class provides the following class methods:

Model.get(keys)

  Gets the model instance (or instances) for the given Key objects. The keys must represent entities of the model's kind. If a provided key is not of the correct kind, a `KindError` is raised.

  This method is similar to the db.get() function, with additional type checking.

  Arguments:

  keys
    A Key object or a list of Key objects. Can also be a string version of a Key object, or list of strings.
Model.get_by_id(ids, parent=None)

  Gets the model instance (or instances) for the given numeric ID (or IDs).

  Arguments:

  ids
    A numeric entity ID, or a list of numeric entity IDs.
  parent
    The parent entity for the requested entities, as a Model instance or Key instance, or `None` (the default) if the requested entities do not have a parent. Multiple entities requested by one call must all have the same parent.

  If ids is a string representing one name, then the method returns the model instance for the name, or `None` if the entity doesn't exist. If ids is a list, the method returns a list of model instances, with a `None` value when no entity exists for a corresponding Key.

Model.get_by_key_name(key_names, parent=None)

  Gets the model instance (or instances) for the given key name (or names).

  Arguments:

  key_names
    A key name, or a list of key names.
  parent
    The parent entity for the requested entities, as a Model instance or Key instance, or `None` (the default) if the requested entities do not have a parent. Multiple entities requested by one call must all have the same parent.

  If key_names is a string representing one name, then the method returns the model instance for the name, or `None` if the entity doesn't exist. If key_names is a list, the method returns a list of model instances, with a `None` value when no entity exists for a corresponding Key.

Model.get_or_insert(key_name, **kwds)

  Get or create an entity of the model's kind with the given key name, using a single transaction. The transaction ensures that if two users attempt to get-or-insert the entity with the given name simultaneously, then both users will have a model instance that refers to the entity, regardless of which process created it.

  Arguments:

  key_name
    The name for the key of the entity
  **kwds
    Keyword arguments to pass to the model class if an instance with the specified key name doesn't exist. The parent argument is required if the desired entity has a parent.

  The method returns an instance of the model class that represents the requested entity, whether it existed or was created by the method. As with all datastore operations, this method can raise a TransactionFailedError if the transaction could not be completed.

Model.all(keys_only=False)

  Returns a Query object that represents all entities for the kind corresponding to this model. Methods on the Query object can apply filters and sort orders to the query before it is executed. See Query for more information

  Arguments:

  keys_only

    Whether the query should return full entities or just keys. Queries that return keys are faster and cost less CPU than queries that return full entities.

Model.gql(query_string, *args, **kwds)

  Performs a GQL query over instances of this model.

  Arguments:

  query_string
    The part of the GQL query following `SELECT * FROM model` (which is implied by using this class method).
  *args
    Positional parameter bindings, similar to the GqlQuery constructor.
  **kwds
    Keyword parameter bindings, similar to the GqlQuery constructor.

      s = Story.gql("WHERE title = :1", "Little Red Riding Hood")

      s = Story.gql("WHERE title = :title", title="Little Red Riding Hood")

  The return value is a GqlQuery object, which can be used to access the results.

Model.kind()
  Returns the kind of the model, usually the name of the Model subclass.
Model.properties()
  Returns a dictionary of all of the properties defined for this model class.

## Instance Methods

Model instances have the following methods:

key()

  Returns the datastore Key for this model instance.

  A model instance does not have a key until it is put() in the datastore. Calling key() before the instance has a key raises a NotSavedError.

put()

  Stores the model instance in the datastore. If the model instance is newly created and has never been stored, this method creates a new data entity in the datastore. Otherwise, it updates the data entity with the current property values.

  The method returns the Key of the stored entity.

delete()

  Deletes the model instance from the datastore. If the instance has never been put(), the delete raises a NotSavedError.

is_saved()

  Returns `True` if the model instance has been put() into the datastore at least once.

  This method only checks that the instance has been stored at least once since it was created. It does not check if the instance's properties have been updated since the last time it was put().

dynamic_properties()

  Returns a list of the names of all of the dynamic properties defined for this model instance. This only applies to instances of Expando classes. For non-Expando model instances, this returns an empty list.

parent()

  Returns a model instance for the parent entity of this instance, or `None` if this instance does not have a parent.

parent_key()

  Returns the Key of the parent entity of this instance, or `None` if this instance does not have a parent.

to_xml()

  Returns an XML representation of the model instance.

  Property values conform to the Atom and GData specifications.

## Disallowed Property Names

The datastore and its API impose several restrictions on names for entity properties and model instance attributes.

The datastore reserves all property names that begin and end with two underscores (`__*__`). A datastore entity cannot have a property with such a name.

The Python model API ignores all attributes on a Model or Expando that begin with an underscore (`_`). Your application can use these attributes to associate data with the model objects that is not saved to the datastore.

Lastly, the Python model API uses object attributes to define properties of a model, and by default the datastore entity properties are named after the attributes. Because the Model class has several properties and methods for other purposes, those attributes cannot be used for properties in the Python API. For example, a Model cannot have a property accessed with the attribute `key`.

However, a property can specify a different name for the datastore than the attribute name by giving a name argument to the property constructor. This allows the datastore entity to have a property name similar to a reserved attribute in the Model class, and use a different attribute name in the class.

    class MyModel(db.Model):
      obj_key = db.StringProperty(name="key")

The following attribute names are reserved by the Model class in the Python API:

`all` `app` `copy` `delete` `entity` `entity_type` `fields` `from_entity` `get` `gql` `instance_properties` | `is_saved` `key` `key_name` `kind` `parent` `parent_key` `properties` `put` `setdefault` `to_xml` `update`