App Engine Python SDK  v1.6.9 rev.445
The Python runtime is available as an experimental Preview feature.
Public Member Functions | Static Public Attributes | List of all members
google.appengine.api.datastore.Query Class Reference
Inheritance diagram for google.appengine.api.datastore.Query:
google.appengine.api.datastore.MultiQuery

Public Member Functions

def __init__
 
def Order
 
def Hint
 
def Ancestor
 
def IsKeysOnly
 
def GetQueryOptions
 
def GetQuery
 
def GetOrder
 
def GetFilterPredicate
 
def GetDistinct
 
def GetIndexList
 
def GetCursor
 
def GetBatcher
 
def Run
 
def Get
 
def Count
 
def __iter__
 
def __getstate__
 
def __setstate__
 
def __setitem__
 
def setdefault
 
def __delitem__
 
def update
 
def copy
 

Static Public Attributes

 ASCENDING = datastore_query.PropertyOrder.ASCENDING
 
 DESCENDING = datastore_query.PropertyOrder.DESCENDING
 
 ORDER_FIRST = datastore_query.QueryOptions.ORDER_FIRST
 
 ANCESTOR_FIRST = datastore_query.QueryOptions.ANCESTOR_FIRST
 
 FILTER_FIRST = datastore_query.QueryOptions.FILTER_FIRST
 
dictionary OPERATORS = {'==': datastore_query.PropertyFilter._OPERATORS['=']}
 
 INEQUALITY_OPERATORS = datastore_query.PropertyFilter._INEQUALITY_OPERATORS
 
tuple UPPERBOUND_INEQUALITY_OPERATORS = frozenset(['<', '<='])
 
tuple FILTER_REGEX
 
 GetCompiledQuery = _GetCompiledQuery
 
 GetCompiledCursor = GetCursor
 

Detailed Description

A datastore query.

(Instead of this, consider using appengine.ext.gql.Query! It provides a
query language interface on top of the same functionality.)

Queries are used to retrieve entities that match certain criteria, including
app id, kind, and property filters. Results may also be sorted by properties.

App id and kind are required. Only entities from the given app, of the given
type, are returned. If an ancestor is set, with Ancestor(), only entities
with that ancestor are returned.

Property filters are used to provide criteria based on individual property
values. A filter compares a specific property in each entity to a given
value or list of possible values.

An entity is returned if its property values match *all* of the query's
filters. In other words, filters are combined with AND, not OR. If an
entity does not have a value for a property used in a filter, it is not
returned.

Property filters map filter strings of the form '<property name> <operator>'
to filter values. Use dictionary accessors to set property filters, like so:

> query = Query('Person')
> query['name ='] = 'Ryan'
> query['age >='] = 21

This query returns all Person entities where the name property is 'Ryan',
'Ken', or 'Bret', and the age property is at least 21.

Another way to build this query is:

> query = Query('Person')
> query.update({'name =': 'Ryan', 'age >=': 21})

The supported operators are =, >, <, >=, and <=. Only one inequality
filter may be used per query. Any number of equals filters may be used in
a single Query.

A filter value may be a list or tuple of values. This is interpreted as
multiple filters with the same filter string and different values, all ANDed
together. For example, this query returns everyone with the tags "google"
and "app engine":

> Query('Person', {'tag =': ('google', 'app engine')})

Result entities can be returned in different orders. Use the Order()
method to specify properties that results will be sorted by, and in which
direction.

Note that filters and orderings may be provided at any time before the query
is run. When the query is fully specified, Run() runs the query and returns
an iterator. The query results can be accessed through the iterator.

A query object may be reused after it's been run. Its filters and
orderings can be changed to create a modified query.

If you know how many result entities you need, use Get() to fetch them:

> query = Query('Person', {'age >': 21})
> for person in query.Get(4):
>   print 'I have four pints left. Have one on me, %s!' % person['name']

If you don't know how many results you need, or if you need them all, you
can get an iterator over the results by calling Run():

> for person in Query('Person', {'age >': 21}).Run():
>   print 'Have a pint on me, %s!' % person['name']

Get() is more efficient than Run(), so use Get() whenever possible.

Finally, the Count() method returns the number of result entities matched by
the query. The returned count is cached; successive Count() calls will not
re-scan the datastore unless the query is changed.

Constructor & Destructor Documentation

def google.appengine.api.datastore.Query.__init__ (   self,
  kind = None,
  filters = {},
  _app = None,
  keys_only = False,
  compile = True,
  cursor = None,
  namespace = None,
  end_cursor = None,
  projection = None,
  distinct = None,
  _namespace = None 
)
Constructor.

Raises BadArgumentError if kind is not a string. Raises BadValueError or
BadFilterError if filters is not a dictionary of valid filters.

Args:
  namespace: string, the namespace to query.
  kind: string, the kind of entities to query, or None.
  filters: dict, initial set of filters.
  keys_only: boolean, if keys should be returned instead of entities.
  projection: iterable of property names to project.
  distinct: boolean, if projection should be distinct.
  compile: boolean, if the query should generate cursors.
  cursor: datastore_query.Cursor, the start cursor to use.
  end_cursor: datastore_query.Cursor, the end cursor to use.
  _namespace: deprecated, use namespace instead.

Member Function Documentation

def google.appengine.api.datastore.Query.__delitem__ (   self,
  filter 
)
Implements the del [] operator. Used to remove filters.
def google.appengine.api.datastore.Query.__setitem__ (   self,
  filter,
  value 
)
Implements the [] operator. Used to set filters.

If the filter string is empty or not a string, raises BadFilterError. If
the value is not a supported type, raises BadValueError.
def google.appengine.api.datastore.Query.Ancestor (   self,
  ancestor 
)
Sets an ancestor for this query.

This restricts the query to only return result entities that are descended
from a given entity. In other words, all of the results will have the
ancestor as their parent, or parent's parent, or etc.

Raises BadArgumentError or BadKeyError if parent is not an existing Entity
or Key in the datastore.

Args:
  # the key must be complete
  ancestor: Entity or Key

Returns:
  # this query
  Query
def google.appengine.api.datastore.Query.copy (   self)
The copy method is not supported.
def google.appengine.api.datastore.Query.Count (   self,
  limit = 1000,
  kwargs 
)
Returns the number of entities that this query matches.

Args:
  limit, a number or None. If there are more results than this, stop short
  and just return this number. Providing this argument makes the count
  operation more efficient.
  config: Optional Configuration to use for this request.

Returns:
  The number of results.
def google.appengine.api.datastore.Query.Get (   self,
  limit,
  offset = 0,
  kwargs 
)
Deprecated, use list(Run(...)) instead.

Args:
  limit: int or long representing the maximum number of entities to return.
  offset: int or long representing the number of entities to skip
  kwargs: Any keyword arguments accepted by datastore_query.QueryOptions().

Returns:
  # a list of entities
  [Entity, ...]
def google.appengine.api.datastore.Query.GetBatcher (   self,
  config = None 
)
Runs this query and returns a datastore_query.Batcher.

This is not intended to be used by application developers. Use Get()
instead!

Args:
  config: Optional Configuration to use for this request.

Returns:
  # an iterator that provides access to the query results
  Iterator
def google.appengine.api.datastore.Query.GetCursor (   self)
Get the cursor from the last run of this query.

The source of this cursor varies depending on what the last call was:
  - Run: A cursor that points immediately after the last result pulled off
the returned iterator.
  - Get: A cursor that points immediately after the last result in the
returned list.
  - Count: A cursor that points immediately after the last result counted.

Returns:
  A datastore_query.Cursor object that can be used in subsequent query
  requests.

Raises:
  AssertionError: The query has not yet been run or cannot be compiled.
def google.appengine.api.datastore.Query.GetDistinct (   self)
Returns True if the current instance is distinct.

Returns:
  A boolean indicating if the distinct flag is set.
def google.appengine.api.datastore.Query.GetFilterPredicate (   self)
Returns a datastore_query.FilterPredicate for the current instance.

Returns:
  datastore_query.FilterPredicate or None if no filters are set on the
  current Query.
def google.appengine.api.datastore.Query.GetIndexList (   self)
Get the index list from the last run of this query.

Returns:
  A list of indexes used by the last run of this query.

Raises:
  AssertionError: The query has not yet been run.
def google.appengine.api.datastore.Query.GetOrder (   self)
Gets a datastore_query.Order for the current instance.

Returns:
  datastore_query.Order or None if there are no sort orders set on the
  current Query.
def google.appengine.api.datastore.Query.GetQuery (   self)
Returns a datastore_query.Query for the current instance.
def google.appengine.api.datastore.Query.GetQueryOptions (   self)
Returns a datastore_query.QueryOptions for the current instance.
def google.appengine.api.datastore.Query.Hint (   self,
  hint 
)
Sets a hint for how this query should run.

The query hint gives us information about how best to execute your query.
Currently, we can only do one index scan, so the query hint should be used
to indicates which index we should scan against.

Use FILTER_FIRST if your first filter will only match a few results. In
this case, it will be most efficient to scan against the index for this
property, load the results into memory, and apply the remaining filters
and sort orders there.

Similarly, use ANCESTOR_FIRST if the query's ancestor only has a few
descendants. In this case, it will be most efficient to scan all entities
below the ancestor and load them into memory first.

Use ORDER_FIRST if the query has a sort order and the result set is large
or you only plan to fetch the first few results. In that case, we
shouldn't try to load all of the results into memory; instead, we should
scan the index for this property, which is in sorted order.

Note that hints are currently ignored in the v3 datastore!

Arg:
  one of datastore.Query.[ORDER_FIRST, ANCESTOR_FIRST, FILTER_FIRST]

Returns:
  # this query
  Query
def google.appengine.api.datastore.Query.IsKeysOnly (   self)
Returns True if this query is keys only, false otherwise.
def google.appengine.api.datastore.Query.Order (   self,
  orderings 
)
Specify how the query results should be sorted.

Result entities will be sorted by the first property argument, then by the
second, and so on. For example, this:

> query = Query('Person')
> query.Order('bday', ('age', Query.DESCENDING))

sorts everyone in order of their birthday, starting with January 1.
People with the same birthday are sorted by age, oldest to youngest.

The direction for each sort property may be provided; if omitted, it
defaults to ascending.

Order() may be called multiple times. Each call resets the sort order
from scratch.

If an inequality filter exists in this Query it must be the first property
passed to Order. Any number of sort orders may be used after the
inequality filter property. Without inequality filters, any number of
filters with different orders may be specified.

Entities with multiple values for an order property are sorted by their
lowest value.

Note that a sort order implies an existence filter! In other words,
Entities without the sort order property are filtered out, and *not*
included in the query results.

If the sort order property has different types in different entities - ie,
if bob['id'] is an int and fred['id'] is a string - the entities will be
grouped first by the property type, then sorted within type. No attempt is
made to compare property values across types.

Raises BadArgumentError if any argument is of the wrong format.

Args:
  # the properties to sort by, in sort order. each argument may be either a
  # string or (string, direction) 2-tuple.

Returns:
  # this query
  Query
def google.appengine.api.datastore.Query.Run (   self,
  kwargs 
)
Runs this query.

If a filter string is invalid, raises BadFilterError. If a filter value is
invalid, raises BadValueError. If an IN filter is provided, and a sort
order on another property is provided, raises BadQueryError.

If you know in advance how many results you want, use limit=#. It's
more efficient.

Args:
  kwargs: Any keyword arguments accepted by datastore_query.QueryOptions().

Returns:
  # an iterator that provides access to the query results
  Iterator
def google.appengine.api.datastore.Query.setdefault (   self,
  filter,
  value 
)
If the filter exists, returns its value. Otherwise sets it to value.

If the property name is the empty string or not a string, raises
BadPropertyError. If the value is not a supported type, raises
BadValueError.
def google.appengine.api.datastore.Query.update (   self,
  other 
)
Updates this query's filters from the ones in other.

If any filter string is invalid, raises BadFilterError. If any value is
not a supported type, raises BadValueError.

Member Data Documentation

tuple google.appengine.api.datastore.Query.FILTER_REGEX
static
Initial value:
1 = re.compile(
2  '^\s*([^\s]+)(\s+(%s)\s*)?$' % '|'.join(OPERATORS),
3  re.IGNORECASE | re.UNICODE)

The documentation for this class was generated from the following file: