Skip to page content Skip to main navigation
English | Site Directory

e.g. "templates" or "datastore"

# The Query Class

The Query class is a datastore query interface that uses objects and methods to prepare queries.

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

- Introduction
- Query()
- Instance methods:
  - filter()
  - order()
  - ancestor()
  - get()
  - fetch()
  - count()

## Introduction

An application creates a Query object either by calling the constructor with the Model class whose entities are to be queried, or by calling the class's all() class method.

    class Song(db.Model):
      title = db.StringProperty()
      composer = db.StringProperty()
      date = db.DateTimeProperty()

    query = db.Query(Song)

    query = Song.all()

Without modification, the object represents a query for all entities of the given kind. Method calls customize the query with property conditions (filter()), ancestor conditions (ancestor()), and ordering (order()). For convenience, these methods return `self` so that they can be chained together in a single statement.

    query.filter('title =', 'Imagine')
    query.order('-date')
    query.ancestor(key)

    query.filter('title =', 'Imagine').order('-date').ancestor(key)

The application executes the query in one of two ways:

- by calling the fetch() method. This performs a single call to the datastore to fetch results, up to the specified number of results. The Query object does not cache results, so calling fetch() a second time will re-execute the query.

      results = query.fetch(limit=5)
      for song in results:
        print song.title

- by treating the Query object as an iterable. The iterator retrieves results from the datastore in small batches, allowing for the app to stop iterating on results to avoid fetching more than is needed. Iteration stops when all of the results that match the query have been retrieved. As with fetch(), the iterator interface does not cache results, so creating a new iterator from the Query object will re-execute the query.

      for song in query:
        print song.title

See also GqlQuery, a query class that uses a SQL-like query language.

Note: The index-based data structures and algorithms that power datastore queries do not support some kinds of queries. See Queries and Indexes: Restrictions on Queries for more information.

## Constructor

The constructor of the Query class is defined as follows:

class Query(model_class)

  A datastore query interface that uses objects and methods to prepare queries.

  The Query instance returned by the constructor represents a query for all entities of the kind. The instance methods filter(), order() and ancestor() apply criteria to the query to filter or order the results.

  Arguments:

  model_class
    The class of the Model (or Expando) that represents the datastore entity kind for the query.

## Instance Methods

Instances of the Query class have the following methods:

filter(property_operator, value)

  Adds a property condition filter to the query. Only entities with properties that meet all of the conditions will be returned by the query.

  Arguments:

  property_operator
    A string containing the property name, and an optional comparison operator. The name and the operator must be separated by a space, as in: `age >` The following comparison operators are supported: `< <= = >= > != IN` If the operator is omitted from the string (the argument is just the property name), the filter uses the `=` operator.
  value
    The value to use in the comparison on the right-hand side of the expression. Its type should be the value data type for the property being compared. See Types and Property Classes.

      query.filter('height >', 42).filter('city = ', 'Seattle')

      query.filter('user = ', users.get_current_user())

order(property)

  Adds an ordering for the results. Results are ordered starting with the first order added.

  Arguments:

  property
    A string, the name of the property to order. To specify that the order ought to be in descending order, precede the name with a hyphen (`-`). Without a hyphen, the order is ascending.

      # Order by last name, alphabetical:
      query.order('last_name')

      # Order tallest to shortest:
      query.order('-height')

ancestor(ancestor)

  Adds an ancestor condition filter to the query. Only entities with the given entity as an ancestor (anywhere in its path) will be returned by the query.

  Arguments:

  ancestor
    A Model instance or Key instance representing the ancestor.
get()

  Executes the query, then returns the first result, or `None` if the query returned no results.

  get() implies a "limit" of 1. At most 1 result is fetched from the datastore.

fetch(limit, offset=0)

  Executes the query, then returns the results.

  The limit and offset arguments control how many results are fetched from the datastore, and how many are returned by the fetch() method:

  - The datastore fetches offset + limit results to the application. The first offset results are not skipped by the datastore itself.
  - The fetch() method skips the first offset results, then returns the rest (limit results).
  - The query has performance characteristics that correspond linearly with the offset amount plus the limit.

  Note: fetch() returns a maximum of 1000 results. If more than 1000 entities match the query, and either no limit is specified or a limit larger than 1000 is used, only the first 1000 results are returned by fetch().

  Arguments:

  limit

    The number of results to return. Fewer than limit results may be returned if not enough results are available that meet the criteria.

    limit is a required argument. To get every result from a query when the number of results is unknown, use the Query object as an iterable instead of using the fetch() method.

  offset
    The number of results to skip.

  The return value is a list of model instances, possibly an empty list.

count(limit)

  Returns the number of results this query fetches.

  count() is somewhat faster than retrieving all of the data by a constant factor, but the running time still grows with the size of the result set. It's best to only use count() in cases where the count is expected to be small, or specify a limit.

  Note: count() returns a maximum of 1000. If the actual number of entities that match the query criteria exceeds the maximum, count() returns a count of 1000.

  Arguments:

  limit

    The maximum number of results to count.