The Model Class Stay organized with collections Save and categorize content based on your preferences.
Note:Developers building new applications arestrongly encouraged to use theNDB Client Library, which has several benefitscompared to this client library, such as automatic entity caching via the MemcacheAPI. If you are currently using the older DB Client Library, read theDB to NDB Migration Guide
ClassModel is the superclass for data model definitions.
Model is defined in the modulegoogle.appengine.ext.db.
Introduction
An application defines a data model by defining a class that subclassesModel. Properties of the model are defined using class attributesandPropertyclass instances. For example:
classStory(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 theModelclass. 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 entitykind. The Datastore reserves all kind names that begin with two underscores(__). Model sub-classes must not use such names.
The names of the attributes are used as the names of the correspondingproperties on an entity. Model instance attributes whose names begin with anunderscore (_) are ignored, so your application can use suchattributes to store data on a model instance that isn't saved to theDatastore.
The Datastore and the model class API impose several restrictions on propertynames and model instance attributes. SeeDisallowed Property Namesfor a complete description.
Every entity has akey,a unique identifier that represents the entity. The key can include an optionalkey name, a string unique across entities of the given kind. Theentity's kind and key name can be used with theKey.from_path()andModel.get_by_key_name()methods to retrieve the entity.
An entity can also have an optionalparententity. Parent-child relationships formentity groups,which are used to control transactionality and data locality in the Datastore.An application creates a parent-child relationship between two entities bypassing the parent entity to the child entity's constructor, as theparent argument.
The methodModel.get_or_insert()can be used to retrieve an entity that may not exist, creating it in theDatastore 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 written (put)for the first time, either explicitly or viaModel.get_or_insert().
To create adict that is a copy of a model instance's data, usethedb.to_dictfunction.
Constructor
The constructor for classModel is defined as follows:
- class Model (parent=None,key_name=None,**kwds)
The superclass for data model definitions.
During construction, each property's
validate()method is called. Exceptions from such calls propagate to callers of this constructor.Arguments
- parent
- The model instance or key for the entity that is the new entity's parent.
- key_name
The key name for the entity. The name becomes part of the primary key. If
None, a system-generated numeric ID is used for the key.The value for
key_namemust not be of the form__*__.The key name is stored as a Unicode string, with
strvalues converted as ASCII text.Calling
put()on this object willoverwrite any existing Datastore entity with the same key.- kwds
- Initial values for the instance's properties, as keyword arguments. Each name corresponds with an attribute defined on the Model class.
Additional keyword argument
- key
The explicit
Keyinstance for the entity. Cannot be used withkey_nameorparent. IfNone, falls back on the behavior forkey_nameandparent. Useful when usingallocate_ids()to reserve numeric IDs for new entities.The value for
keymust be a validKeyinstance.Calling
put()on this object willoverwrite any existing Datastore entity with the same key.
Class Methods
ClassModel has the following class methods:
- Model.get (keys)
Retrieves the model instance (or instances) for the given key (or keys). The keys must represent entities of the model's kind. If a provided key is not of the correct kind, a
KindErrorexception is raised.This method is similar to the
db.get()function, with additional type checking.Arguments
- keys
- Keyof entity to be retrieved, a string representation of the key, or a list of keys or their string representations.
- read_policy
- Read policy specifying desired level of data consistency:
- STRONG_CONSISTENCY
- Guarantees the freshest results, but limited to a singleentity group.
- EVENTUAL_CONSISTENCY
- Can span multiple entity groups, but may occasionally return stale results. In general, eventually consistent queries run faster than strongly consistent queries, but there is no guarantee.
Note: Global (non-ancestor) queries ignore this argument.
- deadline
- Maximum time, in seconds, to wait for Datastore to return a result before aborting with an error. Accepts either an integer or a floating-point value. Cannot be set higher than the default value (60 seconds), but can be adjusted downward to ensure that a particular operation fails quickly (for instance, to return a faster response to the user, retry the operation, try a different operation, or add the operation to a task queue).
If
keysconsists of a single key (or its string representation), this method returns the model instance associated with the key if the key exists in the Datastore, otherwiseNone. Ifkeysis a list, the return value is a corresponding list of model instances, withNonevalues where no entity exists for a given key.See also the
db.get()function.- Model.get_by_id (ids,parent=None)
Retrieves the model instance (or instances) for the given numeric ID (or IDs).
Arguments
- ids
- A numeric entity ID, or a list of numeric IDs.
- parent
- The parent entity for the requested entities, as a model or key, 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. - read_policy
- Read policy specifying desired level of data consistency:
- STRONG_CONSISTENCY
- Guarantees the freshest results, but limited to a singleentity group.
- EVENTUAL_CONSISTENCY
- Can span multiple entity groups, but may occasionally return stale results. In general, eventually consistent queries run faster than strongly consistent queries, but there is no guarantee.
Note: Global (non-ancestor) queries ignore this argument.
- deadline
- Maximum time, in seconds, to wait for Datastore to return a result before aborting with an error. Accepts either an integer or a floating-point value. Cannot be set higher than the default value (60 seconds), but can be adjusted downward to ensure that a particular operation fails quickly (for instance, to return a faster response to the user, retry the operation, try a different operation, or add the operation to a task queue).
If
idsconsists of a single numeric ID, this method returns the model instance associated with the ID if the ID exists in the Datastore, otherwiseNone. Ifidsis a list, the return value is a corresponding list of model instances, withNonevalues where no entity exists for a given numeric ID.- Model.get_by_key_name (key_names,parent=None)
Retrieves 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, 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. - read_policy
- Read policy specifying desired level of data consistency:
- STRONG_CONSISTENCY
- Guarantees the freshest results, but limited to a singleentity group.
- EVENTUAL_CONSISTENCY
- Can span multiple entity groups, but may occasionally return stale results. In general, eventually consistent queries run faster than strongly consistent queries, but there is no guarantee.
Note: Global (non-ancestor) queries ignore this argument.
- deadline
- Maximum time, in seconds, to wait for Datastore to return a result before aborting with an error. Accepts either an integer or a floating-point value. Cannot be set higher than the default value (60 seconds), but can be adjusted downward to ensure that a particular operation fails quickly (for instance, to return a faster response to the user, retry the operation, try a different operation, or add the operation to a task queue).
If
key_namesconsists of a single key name, this method returns the model instance associated with the name if the name exists in the Datastore, otherwiseNone. Ifkey_namesis a list, the return value is a corresponding list of model instances, withNonevalues where no entity exists for a given key name.- Model.get_or_insert (key_name,**kwds)
Attempts to get the entity of the model's kind with the given key name. If it exists,
get_or_insert()simply returns it. If it doesn't exist, a new entity with the given kind, name, and parameters inkwdsis created, stored, and returned.The get and subsequent (possible) put operations are wrapped in a transaction to ensure atomicity. Ths means that
get_or_insert()will never overwrite an existing entity, and will insert a new entity if and only if no entity with the given kind and name exists. In other words,get_or_insert()is equivalent to the following Python code:deftxn(key_name,**kwds):entity=Story.get_by_key_name(key_name,parent=kwds.get('parent'))ifentityisNone:entity=Story(key_name=key_name,**kwds)entity.put()returnentitydefget_or_insert(key_name,**kwargs):returndb.run_in_transaction(txn,key_name,**kwargs)get_or_insert('some key',title="The Three Little Pigs")
Arguments
- key_name
- The name for the key of the entity
- kwds
- Keyword arguments to pass to the model class's constructor if an instance with the specified key name doesn't exist. The
parentargument is required if the desired entity has a parent.
Note:
get_or_insert()does not accept aread_policyordeadlineargument.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
TransactionFailedErrorif the transaction could not be completed.- Model.all (keys_only=False)
Returns a
Queryobject 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; seetheQueryclass page for more information.Arguments
- keys_only
- Whether the query should return full entities or just keys. Queries that return keys are faster and use less CPU time 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*FROMmodel(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
GqlQueryobject, 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
Keyfor this model instance.A model instance's key includes the instance'sentity kind along with a uniqueidentifier. The identifier may be either akey name string, assigned explicitly by the application when the instance is created, or an integernumeric ID, assigned automatically by App Engine when the instance is written (put) to the Datastore. Calling
key()before the instance has been assigned an identifier raises aNotSavedErrorexception.- 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.
If the data could not be committed, raises a
TransactionFailedErrorexception.Arguments
- deadline
- Maximum time, in seconds, to wait for Datastore to return a result before aborting with an error. Accepts either an integer or a floating-point value. Cannot be set higher than the default value (60 seconds), but can be adjusted downward to ensure that a particular operation fails quickly (for instance, to return a faster response to the user, retry the operation, try a different operation, or add the operation to a task queue).
- delete ()
Deletes the model instance from the Datastore. If the instance has never been written (put) to the Datastore, the delete raises a
NotSavedErrorexception.Arguments
- deadline
- Maximum time, in seconds, to wait for Datastore to return a result before aborting with an error. Accepts either an integer or a floating-point value. Cannot be set higher than the default value (60 seconds), but can be adjusted downward to ensure that a particular operation fails quickly (for instance, to return a faster response to the user, retry the operation, try a different operation, or add the operation to a task queue).
- is_saved ()
Returns
Trueif the model instance has been written (put) to the Datastore at least once.This method only checks that the instance has been written to the Datastore at least once since it was created. It doesnot check whether the instance's properties have been updated since the last time it was written.
- 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
Expandoclasses. For non-Expando model instances, this returns an empty list.- parent ()
Returns a model instance for the parent entity of this instance, or
Noneif this instance does not have a parent.- parent_key ()
Returns the
Keyof the parent entity of this instance, orNoneif this instance does not have a parent.- to_xml ()
Returns an XML representation of the model instance.
Disallowed Property Names
The Datastore and its API impose several restrictions on names for entityproperties and model instance attributes.
The Datastore reserves all property names that begin and end with twounderscores (__*__). A Datastore entity cannot have a property withsuch a name.
The Python model API ignores all attributes on aModel orExpandoclass that begin with an underscore (_). Your application can usethese attributes to associate data with the model objects that is not saved tothe Datastore.
Lastly, the Python model API uses object attributes to define properties of amodel, and by default the Datastore entity properties are named after theattributes. Because theModel class has several properties andmethods for other purposes, those attributes cannot be used for properties inthe Python API. For example, a Model cannot have a property accessed with theattributekey.
However, a property can specify a different name for the Datastore than theattribute name by giving aname argument to the propertyconstructor. This allows the Datastore entity to have a property name similar toa reserved attribute in theModel class, and use a differentattribute name in the class.
classMyModel(db.Model):obj_key=db.StringProperty(name="key")
The following attribute names are reserved by theModel class inthe Python API:
|
|
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2025-12-15 UTC.