Python 2.7 has reached end of support
and will be
deprecated
on January 31, 2026. After deprecation, you won't be able to deploy Python 2.7
applications, even if your organization previously used an organization policy to
re-enable deployments of legacy runtimes. Your existing Python
2.7 applications will continue to run and receive traffic after their
deprecation date. We recommend that
you
migrate to the latest supported version of Python.
Stay organized with collections
Save and categorize content based on your preferences.
google.appengine.ext.db.polymodel module
Summary
Support for polymorphic models and queries.
The Model class on its own is only able to support functional polymorphism.
It is possible to create a subclass of Model and then subclass that one as
many generations as necessary and those classes will share all the same
properties and behaviors. The problem is that subclassing Model in this way
places each subclass in their own Kind. This means that it is not possible
to do polymorphic queries. Building a query on a base class will only return
instances of that class from the Datastore, while queries on a subclass will
only return those instances.
This module allows applications to specify class hierarchies that support
polymorphic queries.
Contents
- class google.appengine.ext.db.polymodel.PolyModel(parent=None, key_name=None, _app=None, _from_entity=False, **kwds)source
Bases: google.appengine.ext.db.Model
Base-class for models that supports polymorphic queries.
Use this class to build hierarchies that can be queried based
on their types.
Exampleconsider the following model hierarchy:
Animal
+——+ +——+
|Canine||Feline|
+——+ +——+
|+——-+ +——-+
| | | |
+—+ +—-+ +—+ +——-+
|Dog||Wolf||Cat||Panther|
+—+ +—-+ +—+ +——-+
This class hierarchy has three levels. The first is the “root class”.
All models in a single class hierarchy must inherit from this root. All
models in the hierarchy are stored as the same kind as the root class.
For example, Panther entities when stored to the datastore are of the kind
‘Animal’. Querying against the Animal kind will retrieve Cats, Dogs and
Canines, for example, that match your query. Different classes stored
in the root class’ kind are identified by their class-key. When loaded
from the datastore, it is mapped to the appropriate implementation class.
Polymorphic properties:
Properties that are defined in a given base-class within a hierarchy are
stored in the datastore for all sub-casses only. So, if the Feline class
had a property called ‘whiskers’, the Cat and Panther enties would also
have whiskers, but not Animal, Canine, Dog or Wolf.
Polymorphic queries:
When written to the datastore, all polymorphic objects automatically have
a property called ‘class’ that you can query against. Using this property
it is possible to easily write a GQL query against any sub-hierarchy. For
example, to fetch only Canine objects, including all Dogs and Wolves:
db.GqlQuery(“SELECT * FROM Animal WHERE class=’Canine’”)
And alternate method is to use the ‘all’ or ‘gql’ methods of the Canine
class:
Canine.all()
Canine.gql(‘’)
The ‘class’ property is not meant to be used by your code other than
for queries. Since it is supposed to represents the real Python class
it is intended to be hidden from view.
Root class:
The root class is the class from which all other classes of the hierarchy
inherits from. Each hierarchy has a single root class. A class is a
root class if it is an immediate child of PolyModel. The subclasses of
the root class are all the same kind as the root class. In other words:
Animal.kind() == Feline.kind() == Panther.kind() == ‘Animal’
- classmethod all(**kwds)source
Get all instance of a class hierarchy.
Parameterskwds – Keyword parameters passed on to Model.all.
ReturnsQuery with filter set to match this class’ discriminator.
- classmethod class_key()source
Calculate the class-key for this class.
ReturnsClass key for class. By default this is a the list of classes
of the hierarchy, starting with the root class and walking its way
down to cls.
- classmethod class_name()source
Calculate class name for this class.
Returns name to use for each classes element within its class-key. Used
to discriminate between different classes within a class hierarchy’s
Datastore kind.
The presence of this method allows developers to use a different class
name in the datastore from what is used in Python code. This is useful,
for example, for renaming classes without having to migrate instances
already written to the datastore. For example, to rename a polymorphic
class Contact to SimpleContact, you could convert:
# Class key is [‘Information’]
class Information(PolyModel): …
# Class key is [‘Information’, ‘Contact’]
class Contact(Information): …
to:
# Class key is still [‘Information’, ‘Contact’]
class SimpleContact(Information):
…
@classmethod
def class_name(cls):
return ‘Contact’
# Class key is [‘Information’, ‘Contact’, ‘ExtendedContact’]
class ExtendedContact(SimpleContact): …
This would ensure that all objects written previously using the old class
name would still be loaded.
ReturnsName of this class.
- classmethod from_entity(entity)source
Load from entity to class based on discriminator.
Rather than instantiating a new Model instance based on the kind
mapping, this creates an instance of the correct model class based
on the entities class-key.
Parametersentity – Entity loaded directly from datastore.
RaisesKindError when there is no class mapping based on discriminator.
- classmethod gql(query_string, *args, **kwds)source
Returns a polymorphic query using GQL query string.
This query is polymorphic in that it has its filters configured in a way
to retrieve instances of the model or an instance of a subclass of the
model.
Parameters
-
query_string – properly formatted GQL query string with the
‘SELECT * FROM <entity>’ part omitted
-
*args – rest of the positional arguments used to bind numeric references
in the query.
-
**kwds – dictionary-based arguments (for named parameters).
- classmethod kind()source
Get kind of polymorphic model.
Overridden so that all subclasses of root classes are the same kind
as the root.
ReturnsKind of entity to write to datastore.
- class google.appengine.ext.db.polymodel.PolymorphicClass(name, bases, dct)source
-
Bases: google.appengine.ext.db.PropertiedClass
Meta-class for initializing PolymorphicClasses.
This class extends PropertiedClass to add a few static attributes to
new polymorphic classes necessary for their correct functioning.
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-06-16 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-06-16 UTC."],[[["\u003cp\u003eThe \u003ccode\u003ePolyModel\u003c/code\u003e class in the \u003ccode\u003egoogle.appengine.ext.db.polymodel\u003c/code\u003e module enables the creation of class hierarchies that support polymorphic queries, where queries on a base class can return instances of any of its subclasses.\u003c/p\u003e\n"],["\u003cp\u003eAll models within a \u003ccode\u003ePolyModel\u003c/code\u003e hierarchy are stored under the same "kind" as the root class, allowing for retrieval of different types through a single query.\u003c/p\u003e\n"],["\u003cp\u003ePolymorphic properties defined in a base-class are shared among its subclasses, but not by the root or other unrelated classes.\u003c/p\u003e\n"],["\u003cp\u003eThe 'class' property is automatically added to all polymorphic objects in the datastore, enabling queries to target specific sub-hierarchies using GQL.\u003c/p\u003e\n"],["\u003cp\u003eThe root class of a given hierarchy is a direct child of \u003ccode\u003ePolyModel\u003c/code\u003e, with all of it's subclasses sharing the same "kind" as the root.\u003c/p\u003e\n"]]],[],null,["# google.appengine.ext.db.polymodel module\n========================================\n\nSummary\n-------\n\nSupport for polymorphic models and queries.\n\nThe Model class on its own is only able to support functional polymorphism.\nIt is possible to create a subclass of Model and then subclass that one as\nmany generations as necessary and those classes will share all the same\nproperties and behaviors. The problem is that subclassing Model in this way\nplaces each subclass in their own Kind. This means that it is not possible\nto do polymorphic queries. Building a query on a base class will only return\ninstances of that class from the Datastore, while queries on a subclass will\nonly return those instances.\n\nThis module allows applications to specify class hierarchies that support\npolymorphic queries.\n\nContents\n--------\n\n*class* google.appengine.ext.db.polymodel.PolyModel(parent=None, key_name=None, _app=None, _from_entity=False, \\*\\*kwds)[source](/appengine/docs/legacy/standard/python/refdocs/modules/google/appengine/ext/db/polymodel#PolyModel)\n\n: Bases: [google.appengine.ext.db.Model](/appengine/docs/legacy/standard/python/refdocs/google.appengine.ext.db#google.appengine.ext.db.Model)\n\n Base-class for models that supports polymorphic queries.\n\n Use this class to build hierarchies that can be queried based\n on their types.\n Example\n\n consider the following model hierarchy:\n\n Animal\n\n +------+ +------+\n \\|Canine\\|\\|Feline\\|\n +------+ +------+\n \\|\n\n +-------+ +-------+\n \\| \\| \\| \\|\n\n +---+ +----+ +---+ +-------+\n \\|Dog\\|\\|Wolf\\|\\|Cat\\|\\|Panther\\|\n +---+ +----+ +---+ +-------+\n\n This class hierarchy has three levels. The first is the \"root class\".\n All models in a single class hierarchy must inherit from this root. All\n models in the hierarchy are stored as the same kind as the root class.\n For example, Panther entities when stored to the datastore are of the kind\n 'Animal'. Querying against the Animal kind will retrieve Cats, Dogs and\n Canines, for example, that match your query. Different classes stored\n in the root class' kind are identified by their class-key. When loaded\n from the datastore, it is mapped to the appropriate implementation class.\n\n Polymorphic properties:\n\n Properties that are defined in a given base-class within a hierarchy are\n stored in the datastore for all sub-casses only. So, if the Feline class\n had a property called 'whiskers', the Cat and Panther enties would also\n have whiskers, but not Animal, Canine, Dog or Wolf.\n\n Polymorphic queries:\n\n When written to the datastore, all polymorphic objects automatically have\n a property called 'class' that you can query against. Using this property\n it is possible to easily write a GQL query against any sub-hierarchy. For\n example, to fetch only Canine objects, including all Dogs and Wolves:\n\n db.GqlQuery(\"SELECT \\* FROM Animal WHERE class='Canine'\")\n\n And alternate method is to use the 'all' or 'gql' methods of the Canine\n class:\n\n Canine.all()\n Canine.gql('')\n\n The 'class' property is not meant to be used by your code other than\n for queries. Since it is supposed to represents the real Python class\n it is intended to be hidden from view.\n\n Root class:\n\n The root class is the class from which all other classes of the hierarchy\n inherits from. Each hierarchy has a single root class. A class is a\n root class if it is an immediate child of PolyModel. The subclasses of\n the root class are all the same kind as the root class. In other words:\n\n Animal.kind() == Feline.kind() == Panther.kind() == 'Animal' \n\n *classmethod* all(\\*\\*kwds)[source](/appengine/docs/legacy/standard/python/refdocs/modules/google/appengine/ext/db/polymodel#PolyModel.all)\n\n : Get all instance of a class hierarchy.\n\n Parameters\n\n kwds -- Keyword parameters passed on to Model.all.\n Returns\n\n Query with filter set to match this class' discriminator. \n\n *classmethod* class_key()[source](/appengine/docs/legacy/standard/python/refdocs/modules/google/appengine/ext/db/polymodel#PolyModel.class_key)\n\n : Calculate the class-key for this class.\n\n Returns\n\n Class key for class. By default this is a the list of classes\n of the hierarchy, starting with the root class and walking its way\n down to cls. \n\n *classmethod* class_name()[source](/appengine/docs/legacy/standard/python/refdocs/modules/google/appengine/ext/db/polymodel#PolyModel.class_name)\n\n : Calculate class name for this class.\n\n Returns name to use for each classes element within its class-key. Used\n to discriminate between different classes within a class hierarchy's\n Datastore kind.\n\n The presence of this method allows developers to use a different class\n name in the datastore from what is used in Python code. This is useful,\n for example, for renaming classes without having to migrate instances\n already written to the datastore. For example, to rename a polymorphic\n class Contact to SimpleContact, you could convert:\n\n # Class key is \\['Information'\\]\n class Information(PolyModel): ...\n\n # Class key is \\['Information', 'Contact'\\]\n class Contact(Information): ...\n\n to:\n\n # Class key is still \\['Information', 'Contact'\\]\n class SimpleContact(Information):\n\n ...\n @classmethod\n def class_name(cls):\n\n return 'Contact'\n\n # Class key is \\['Information', 'Contact', 'ExtendedContact'\\]\n class ExtendedContact(SimpleContact): ...\n\n This would ensure that all objects written previously using the old class\n name would still be loaded.\n Returns\n\n Name of this class. \n\n *classmethod* from_entity(entity)[source](/appengine/docs/legacy/standard/python/refdocs/modules/google/appengine/ext/db/polymodel#PolyModel.from_entity)\n\n : Load from entity to class based on discriminator.\n\n Rather than instantiating a new Model instance based on the kind\n mapping, this creates an instance of the correct model class based\n on the entities class-key.\n Parameters\n\n entity -- Entity loaded directly from datastore.\n Raises\n\n KindError when there is no class mapping based on discriminator. \n\n *classmethod* gql(query_string, \\*args, \\*\\*kwds)[source](/appengine/docs/legacy/standard/python/refdocs/modules/google/appengine/ext/db/polymodel#PolyModel.gql)\n\n : Returns a polymorphic query using GQL query string.\n\n This query is polymorphic in that it has its filters configured in a way\n to retrieve instances of the model or an instance of a subclass of the\n model.\n Parameters\n\n - query_string -- properly formatted GQL query string with the\n 'SELECT \\* FROM \\\u003centity\\\u003e' part omitted\n\n - \\*args -- rest of the positional arguments used to bind numeric references\n in the query.\n\n - \\*\\*kwds -- dictionary-based arguments (for named parameters).\n\n *classmethod* kind()[source](/appengine/docs/legacy/standard/python/refdocs/modules/google/appengine/ext/db/polymodel#PolyModel.kind)\n\n : Get kind of polymorphic model.\n\n Overridden so that all subclasses of root classes are the same kind\n as the root.\n Returns\n\nKind of entity to write to datastore. \n\n*class* google.appengine.ext.db.polymodel.PolymorphicClass(name, bases, dct)[source](/appengine/docs/legacy/standard/python/refdocs/modules/google/appengine/ext/db/polymodel#PolymorphicClass)\n\n: Bases: [google.appengine.ext.db.PropertiedClass](/appengine/docs/legacy/standard/python/refdocs/google.appengine.ext.db#google.appengine.ext.db.PropertiedClass)\n\n Meta-class for initializing PolymorphicClasses.\n\n This class extends PropertiedClass to add a few static attributes to\n new polymorphic classes necessary for their correct functioning."]]