Note: Developers building new applications are strongly encouraged to use the NDB Client Library, which has several benefits compared to this client library, such as automatic entity caching via the Memcache API. If you are currently using the older DB Client Library, read the DB to NDB Migration Guide
The App Engine datastore supports a fixed set of value types for properties on data entities.
Property
classes can define new types that are converted to and from the underlying value types, and the value types can be used directly with
Expando
dynamic properties and
ListProperty
aggregate property models.
The following table describes the Property classes whose values correspond directly with the underlying data types. Any of these value types can be used in an Expando dynamic property or ListProperty aggregate type.
Datastore Value Types
Datastore entity property values can be of one of the following types. See above for a list of corresponding
Property
classes to use with
Model
definitions.
Other than the Python standard types and
users.User,
all classes described in this section are provided by the google.appengine.ext.db module.
strorunicode-
A short string (1500 bytes or less).
A
strvalue is assumed to be text encoded with theasciicodec, and is converted to aunicodevalue before being stored. The value is returned by the datastore as aunicodevalue. For short strings using other codecs, use aunicodevalue.Short strings are indexed by the datastore, and can be used in filters and sort orders. For text strings longer than 1500 bytes (which are not indexed), use a
Textinstance. For unencoded byte strings longer than 1500 bytes (also not indexed), use aBlobinstance. For non-textual unencoded byte strings up to 1500 bytes (not characters) that should be indexed, use aByteStringinstance.Model property:
StringProperty bool-
A Boolean value (
TrueorFalse).Model property:
BooleanProperty intorlong-
An integer value, up to 64 bits.
Python
intvalues are converted to Pythonlongvalues prior to storage. A value stored as anintwill be returned as along.If a
longlarger than 64 bits is assigned, only the least significant 64 bits are stored.Model property:
IntegerProperty float-
A floating-point number.
Model property:
FloatProperty datetime.datetime-
A date and time. See the
datetimemodule documentation.If the
datetimevalue has atzinfoattribute, it will be converted to the UTC time zone for storage. Values come back from the datastore as UTC, with atzinfoofNone. An application that needs date and time values to be in a particular time zone must settzinfocorrectly when updating the value, and convert values to the timezone when accessing the value.Some libraries use the
TZenvironment variable to control the time zone applied to date-time values. App Engine sets this environment variable to"UTC". Note that changing this variable in an application will not change the behavior of some datetime functions, because changes to environment variables are not visible outside of the Python code.If you only convert values to and from a particular time zone, you can implement a custom
datetime.tzinfoto convert values from the datastore:import datetime import time class Pacific_tzinfo(datetime.tzinfo): """Implementation of the Pacific timezone.""" def utcoffset(self, dt): return datetime.timedelta(hours=-8) + self.dst(dt) def _FirstSunday(self, dt): """First Sunday on or after dt.""" return dt + datetime.timedelta(days=(6-dt.weekday())) def dst(self, dt): # 2 am on the second Sunday in March dst_start = self._FirstSunday(datetime.datetime(dt.year, 3, 8, 2)) # 1 am on the first Sunday in November dst_end = self._FirstSunday(datetime.datetime(dt.year, 11, 1, 1)) if dst_start <= dt.replace(tzinfo=None) < dst_end: return datetime.timedelta(hours=1) else: return datetime.timedelta(hours=0) def tzname(self, dt): if self.dst(dt) == datetime.timedelta(hours=0): return "PST" else: return "PDT" pacific_time = datetime.datetime.fromtimestamp(time.mktime(utc_time.timetuple()), Pacific_tzinfo())
See the
datetimemodule documentation (includingdatetime.tzinfo). See also the third-party modulepytz, though note that thepytzdistribution has many files.The
DateTimePropertymodel property class includes features such as the ability to automatically use the date and time a model instance is stored. These are features of the model, and are not available on the raw datastore value (such as in anExpandodynamic property).Model properties:
DateTimeProperty,DateProperty,TimeProperty list-
A list of values, each of which is of one of the supported data types.
When a
listis used as the value of anExpandodynamic property, it cannot be an empty list. This is due to how list values are stored: When a list property has no items, it has no representation in the datastore. You can use a static property and theListPropertyclass to represent an empty list value for a property.Model property:
ListProperty -
db.Key -
The key for another datastore entity.
Note: Key strings are limited to 1500 bytes or less.
m = Employee(name="Susan", key_name="susan5") m.put() e = Employee(name="Bob", manager=m.key()) e.put() m_key = db.Key.from_path("Employee", "susan5") e = Employee(name="Jennifer", manager=m_key)
Model properties:
ReferenceProperty,SelfReferenceProperty -
blobstore.BlobKey -
The key for a Blobstore value, generated by the Blobstore when the value is uploaded.
Model properties:
blobstore.BlobReferenceProperty -
users.User -
A user with a Google account.
A
user.Uservalue in the datastore does not get updated if the user changes their email address. For this reason, we strongly recommend that you avoid storing ausers.Useras aUserPropertyvalue, because this includes the email address along with the unique ID. If a user changes the email address and you then compare the old, storeduser.Userto the newuser.Uservalue, they won't match. Instead, use theuser.Uservalue'suser_id()as the user's stable unique identifier.Model property:
UserProperty - class Blob(arg=None)
-
Binary data, as a byte string. This is a subclass of the built-in
strtype.Blob properties are not indexed, and cannot be used in filters or sort orders.
Blob is for binary data, such as images. It takes a
strvalue, but this value is stored as a byte string and is not encoded as text. Use aTextinstance for large text data.Model property:
BlobPropertyclass MyModel(db.Model): blob = db.BlobProperty() m = MyModel() m.blob = db.Blob(open("image.png", "rb").read())
In XML, blobs are base-64 encoded whether or not they contain binary data.
- class ByteString(arg)
-
A short blob value (a "byte string") of 1500 bytes or less. ByteString is a subclass of
str, and takes an unencodedstrvalue as an argument to its constructor.ByteStrings are indexed by the datastore, and can be used in filters and sort orders. For byte strings longer than 1500 bytes (which are not indexed), use a
Blobinstance. For encoded text data, usestr(short, indexed) orText(long, not indexed).Model property:
ByteStringProperty - class Text(arg=None, encoding=None)
-
A long string. This is a subclass of the built-in
unicodetype.arg a
unicodeorstrvalue. If arg is astr, then it is parsed with the encoding specified by encoding, orasciiif no encoding is specified. See the list of standard encodings for possible values for encoding.Unlike an entity property whose value is a simple
strorunicode, a Text property can be more than 1500 bytes long. However, Text properties are not indexed, and cannot be used in filters or sort orders.Model property:
TextPropertyclass MyModel(db.Model): text = db.TextProperty() m = MyModel() m.text = db.Text(u"kittens") m.text = db.Text("kittens", encoding="latin-1")
- class Category(tag)
-
A category or "tag". This is a subclass of the built-in
unicodetype.Model property:
CategoryPropertyclass MyModel(db.Model): category = db.CategoryProperty() m = MyModel() m.category = db.Category("kittens")
In XML, this is an Atom
Categoryelement. - class Email(email)
-
An email address. This is a subclass of the built-in
unicodetype.Neither the property class nor the value class perform validation of email addresses, they just store the value.
Model property:
EmailPropertyclass MyModel(db.Model): email_address = db.EmailProperty() m = MyModel() m.email_address = db.Email("larry@example.com")
In XML, this is a
gd:emailelement. - class GeoPt(lat, lon=None)
-
A geographical point represented by floating-point latitude and longitude coordinates.
Model property:
GeoPtPropertyIn XML, this is a
georss:pointelement. - class IM(protocol, address=None)
-
An instant messaging handle.
protocol is the canonical URL of the instant messaging service. Some possible values:
Protocol Description sip SIP/SIMPLE xmpp XMPP/Jabber http://aim.com/ AIM http://icq.com/ ICQ http://messenger.msn.com/ MSN Messenger http://messenger.yahoo.com/ Yahoo Messenger http://sametime.com/ Lotus Sametime http://gadu-gadu.pl/ Gadu-Gadu unknown Unknown or unspecified address is the handle's address.
Model property:
IMPropertyclass MyModel(db.Model): im = db.IMProperty() m = MyModel() m.im = db.IM("http://example.com/", "Larry97")
In XML, this is a
gd:imelement. - class Link(link)
-
A fully qualified URL. This is a subclass of the built-in
unicodetype.Model property:
LinkPropertyclass MyModel(db.Model): link = db.LinkProperty() m = MyModel() m.link = db.Link("http://www.google.com/")
In XML, this is an Atom
Linkelement. - class PhoneNumber(phone)
-
A human-readable telephone number. This is a subclass of the built-in
unicodetype.Model property:
PhoneNumberPropertyclass MyModel(db.Model): phone = db.PhoneNumberProperty() m = MyModel() m.phone = db.PhoneNumber("1 (206) 555-1212")
In XML, this is a
gd.phoneNumberelement. - class PostalAddress(address)
-
A postal address. This is a subclass of the built-in
unicodetype.Model property:
PostalAddressPropertyclass MyModel(db.Model): address = db.PostalAddressProperty() m = MyModel() m.address = db.PostalAddress("1600 Ampitheater Pkwy., Mountain View, CA")
In XML, this is a
gd:postalAddresselement. - class Rating(rating)
-
A user-provided rating for a piece of content, as an integer between 0 and 100. This is a subclass of the built-in
longtype. The class validates that the value is an integer between 0 and 100, and raises aBadValueErrorif the value is invalid.Model property:
RatingPropertyclass MyModel(db.Model): rating = db.RatingProperty() m = MyModel() m.rating = db.Rating(97)
In XML, this is a
gd:ratingelement.
Property Classes
All model property classes provided by google.appengine.ext.db are subclasses of the base class
Property,
and support all of the base constructor's arguments. See the base class documentation for information about those arguments.
The google.appengine.ext.db package provides the following model property classes:
- class BlobProperty(...)
-
An uninterpreted collection of binary data.
Blob data is a byte string. For text data, which may involve encoding, use
TextProperty.Value type:
Blob - class BooleanProperty(...)
-
A Boolean value (
TrueorFalse).Value type:
bool - class ByteStringProperty(verbose_name=None, ...)
-
A short blob value (a "byte string") of 1500 bytes or less.
ByteStringPropertyvalues are indexed, and can be used in filters and sort orders.Like
StringProperty, except that the value is not encoded in any way. The bytes are stored literally.If the
ByteStringPropertyis required, the value cannot be an empty string.Value type:
ByteString - class CategoryProperty(...)
-
A category or "tag," a descriptive word or phrase.
Value type:
Category - class DateProperty(verbose_name=None, auto_now=False, auto_now_add=False, ...)
-
A date without a time of day; see
DateTimePropertyfor more information.Value type:
datetime.date; converted internally todatetime.datetime - class DateTimeProperty(verbose_name=None, auto_now=False, auto_now_add=False, ...)
-
A date and time.
If auto_now is
True, the property value is set to the current time whenever the model instance is stored in the datastore, overwriting the property's previous value. This is useful for tracking a "last modified" date and time for a model instance.If auto_now_add is
True, the property value is set to the current time the first time the model instance is stored in the datastore, unless the property has already been assigned a value. This is useful for storing a "created" date and time for a model instance.Date-time values are stored as and returned using the UTC time zone. See
datetime.datetimefor a discussion of how to manage time zones.Value type:
datetime.datetime - class EmailProperty(...)
-
An email address.
Neither the property class nor the value class perform validation of email addresses, they just store the value.
Value type:
Email - class FloatProperty(...)
-
A floating-point number.
Value type:
float - class GeoPtProperty(...)
-
A geographical point represented by floating-point latitude and longitude coordinates.
Value type:
GeoPt - class IMProperty(...)
-
An instant messaging handle.
Value type:
IM - class IntegerProperty(...)
-
An integer value, up to 64 bits.
Python
intvalues are converted to Pythonlongvalues prior to storage. A value stored as anintwill be returned as along.If a
longlarger than 64 bits is assigned, only the least significant 64 bits are stored. - class LinkProperty(...)
-
A fully qualified URL.
Value type:
Link - class ListProperty(item_type, verbose_name=None, default=None, ...)
-
A list of values of the type specified by item_type.
In a query, comparing a list property to a value performs the test against the members of the list:
list_property=valuetests whether the value appears anywhere in the list,list_property<valuetests whether any of the list members are less than the given value, and so forth.A query cannot compare two list values. There is no way to test two lists for equality without testing each element for membership separately.
item_type is the type of the items in the list, as a Python type or class. All items in the list value must be of the given type. item_type must be one of the datastore value types, and cannot be
list.The value of a
ListPropertycannot beNone. It can, however, be an empty list. WhenNoneis specified for the default argument (or when the default argument is not specified), the default value of the property is the empty list.Tip: Because
ListPropertyaggregate types do not use thePropertyclasses,Propertyclass features such as automatic values and validation are not applied automatically to members of the list value. If you want to validate a member value using aPropertyclass, you can instantiate the class and call itsvalidate()method on the value.default is the default value for the list property. If
None, the default is an empty list. A list property can define a custom validator to disallow the empty list.See the Data Modeling page for more information on list properties and values.
Value type: a Python
listof values of the specified type - class PhoneNumberProperty(...)
-
A human-readable telephone number.
Value type:
PhoneNumber - class PostalAddressProperty(...)
-
A postal address.
Value type:
PostalAddress - class RatingProperty()
-
A user-provided rating for a piece of content, as an integer between 0 and 100.
Value type:
Rating - class ReferenceProperty(reference_class=None, verbose_name=None, collection_name=None, ...)
-
A reference to another model instance. For example, a reference may indicate a many-to-one relationship between the model with the property and the model referenced by the property.
reference_class is the model class of the model instance being referenced. If specified, only model instances of the class can be assigned to this property. If
None, any model instance can be the value of this property.collection_name is the name of the property to give to the referenced model class. The value of the property is a
Queryfor all entities that reference the entity. If no collection_name is set, thenmodelname_set(with the name of the referenced model in lowercase letters and_setadded) is used.Note: collection_name must be set if there are multiple properties within the same model referencing the same model class. Otherwise, a
DuplicatePropertyErrorwill be raised when the default names are generated.ReferencePropertyautomatically references and dereferences model instances as property values: a model instance can be assigned to a reference property directly, and its key will be used. TheReferencePropertyvalue can be used as if it were a model instance, and the datastore entity will be fetched and the model instance created when it is first used in this way. Untouched reference properties do not query for unneeded data.class Author(db.Model): name = db.StringProperty() class Story(db.Model): author = db.ReferenceProperty(Author) story = db.get(story_key) author_name = story.author.name author = db.get(author_key) stories_by_author = author.story_set.get()
As with a
Keyvalue, it is possible for a reference property value to refer to a data entity that does not exist. If a referenced entity is deleted from the datastore, references to the entity are not updated. Accessing an entity that does not exist raises aReferencePropertyResolveError.Deleting an entity does not delete entities referred to by a reference property.
Value type:
db.Key - class SelfReferenceProperty(verbose_name=None, collection_name=None, ...)
-
A reference to another model instance of the same class (see
ReferenceProperty).Value type:
db.Key - class StringListProperty(verbose_name=None, default=None, ...)
-
Similar to a list property of Python
strorunicode(basestring) values. - class StringProperty(verbose_name=None, multiline=False, ...)
-
A short string. Takes a Python
strorunicode(basestring) value of 1500 bytes or less.StringPropertyvalues are indexed, and can be used in filters and sort orders.If multiline is
False, the value cannot include linefeed characters. Thedjangoformslibrary uses this to enforce a difference between text fields and textarea fields in the data model, and others can use it for a similar purpose.If the string property is required, its value cannot be an empty string.
- class TextProperty()
-
A long string.
Unlike
StringProperty, aTextPropertyvalue can be more than 1500 bytes long. However,TextPropertyvalues are not indexed and cannot be used in filters or sort orders.TextPropertyvalues store text with a text encoding. For binary data, useBlobProperty.If the text property is required, its value cannot be an empty string.
Value type:
Text - class TimeProperty(verbose_name=None, auto_now=False, auto_now_add=False, ...)
-
A time of day without a date. Takes a Python standard library
datetime.timevalue; seeDateTimePropertyfor more information.Value type:
datetime.time; converted internally todatetime.datetime - class UserProperty(verbose_name=None, auto_current_user=False, auto_current_user_add=False, ...)
-
Important: We strongly recommend that you do not store a
UserProperty, since it includes the email address and the user's unique ID. If a user changes their email address and you compare their old, storedUserto the newUservalue, they won't match.A user with a Google account.
If auto_current_user is
True, the property value is set to the currently signed-in user whenever the model instance is stored in the datastore, overwriting the property's previous value. This is useful for tracking which user modifies a model instance.If auto_current_user_add is
True, the property value is set to the currently signed-in user the first time the model instance is stored in the datastore, unless the property has already been assigned a value. This is useful for tracking which user creates a model instance, which may not be the same user that modifies it later.UserProperty does not accept a default value. Default values are set when the model class is first imported, and with import caching may not be the currently signed-in user.
Value type:
users.User