Stay organized with collections Save and categorize content based on your preferences.
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
Class Query
represents a query for retrieving entities from the App Engine Datastore. (See also the related class GqlQuery
, which defines queries using GQL, a SQL-like query language.)
Query
is defined in the module google.appengine.ext.db
.
Note: The index-based query mechanism supports a wide range of queries and is suitable for most applications. However, it does not support some kinds of query common in other database technologies: in particular, joins and aggregate queries aren't supported within the Datastore query engine. See Datastore Queries page for limitations on Datastore queries.
IntroductionAn application creates a query object for a given entity kind by calling either the Query
constructor directly
class Song(db.Model): title = db.StringProperty() composer = db.StringProperty() date = db.DateTimeProperty() q = db.Query(Song)
or the class method all()
of the kind's model class:
q = Song.all()
Without further modification, the resulting instance of class Query
will retrieve all existing entities of the specified kind. Method calls on the object can then be used to customize the query with additional filter criteria, ancestor conditions, and sort orders:
q.filter('title =', 'Imagine') q.ancestor(ancestor_key) q.order('-date')
For convenience, all of these methods return the query object itself so that they can cascaded in a single statement:
q.filter('title =', 'Imagine').ancestor(key).order('-date')
The application can then execute the query and access the results in any of the following ways:
Treat the query object as an iterable, to process matching entities one at a time:
for song in q: print song.title
This implicitly calls the query's run()
method to generate the matching entities. It is thus equivalent to
for song in q.run(): print song.title
You can set a limit on the number of results to process with the keyword argument limit
:
for song in q.run(limit=5): print song.title
The iterator interface does not cache results, so creating a new iterator from the query object reiterates the same query from the beginning.
Call the query's get()
method, to obtain the first single matching entity found in the Datastore:
song = q.get() print song.title
Call the query's fetch()
method, to obtain a list of all matching entities up to a specified number of results:
results = q.fetch(limit=5) for song in results: print song.title
As with run()
, the query object does not cache results, so calling fetch()
a second time reissues the same query.
Note: You should rarely need to use this method; it is almost always better to use run()
instead.
The constructor for class Query
is defined as follows:
Creates an instance of class Query
for retrieving entities from the App Engine Datastore.
Without further modification, the resulting query object will retrieve all existing entities of the kind specified by model_class
. The instance methods filter()
, ancestor(),
and order()
can then be used to customize the query with additional filter criteria, ancestor conditions, and sort orders.
Arguments
true
, return only keys instead of complete entities. Keys-only queries are faster and cheaper than those that return complete entities.
Note: Specifying this parameter may change the query's index requirements.
Instances of class Query
have the following methods:
Adds a property filter to the query. The query will return only entities whose properties satisfy all of its filters.
Arguments
=
, !=
, <
, <=
, >
, >=
, IN
), separated by a space: for example, 'age
>'
. If just a property name is specified without a comparison operator, the filter compares for equality (=
) by default.
q.filter('height >', 42).filter('city =', 'Seattle') q.filter('user =', users.get_current_user())
The comparison value specified should be of the same value type as that of the property being compared.
Adds an ancestor filter to the query. The query will return only entities with the specified ancestor.
Argument
Adds a sort order to the query. If more than one sort order is added, they will be applied in the order specified.
Argument
-
) to specify descending order. Omitting the hyphen specifies ascending order by default. For example:
# Order alphabetically by last name: q.order('last_name') # Order by height, tallest to shortest: q.order('-height')
Returns the tuple of properties in the projection or None
.
Returns a boolean value indicating whether the query is a keys-only query.
Returns an iterable for looping over the results of the query. This allows you to specify the query's operation with parameter settings and access the results iteratively:
offset
argument.limit
argument.The loop's performance thus scales linearly with the sum of offset
+ limit
. If you know how many results you want to retrieve, you should always set an explicit limit
value.
This method uses asynchronous prefetching to improve performance. By default, it retrieves its results from the Datastore in small batches, allowing the application to stop the iteration and avoid retrieving more results than are needed.
Tip: To retrieve all available results when their number is unknown, set batch_size
to a large value, such as 1000
.
Tip: If you don't need to change the default argument values, you can just use the query object directly as an iterable to control the loop. This implicitly calls run()
with default arguments.
Arguments
Note: Global (non-ancestor) queries ignore this argument.
None
, all available results will be retrieved by default.
limit
is set, defaults to the specified limit; otherwise defaults to 20
.
true
, return only keys instead of complete entities. Keys-only queries are faster and cheaper than those that return complete entities.
Note: Specifying this parameter may change the query's index requirements.
Executes the query and returns the first result, or None
if no results are found.
Arguments
Note: Global (non-ancestor) queries ignore this argument.
true
, return only keys instead of complete entities. Keys-only queries are faster and cheaper than those that return complete entities.
Note: Specifying this parameter may change the query's index requirements.
Executes the query and returns a (possibly empty) list of results:
offset
argument.limit
argument.The method's performance thus scales linearly with the sum of offset
+ limit
.
Note: This method is merely a thin wrapper around the run()
method, and is less efficient and more memory-intensive than using run()
directly. You should rarely need to use fetch()
; it is provided mainly for convenience in cases where you need to retrieve a full in-memory list of query results.
Tip: The fetch()
method is designed to retrieve only the number of results specified by the limit
argument. To retrieve all available results of a query when their number is unknown, use run()
with a large batch size, such as run(batch_size=1000)
, instead of fetch()
.
Arguments
None
, all available results will be retrieved.
Note: Global (non-ancestor) queries ignore this argument.
true
, return only keys instead of complete entities. Keys-only queries are faster and cheaper than those that return complete entities.
Note: Specifying this parameter may change the query's index requirements.
Returns the number of results matching the query. This is faster by a constant factor than actually retrieving all of the results, but the running time still scales linearly with the sum of offset
+ limit
. Unless the result count is expected to be small, it is best to specify a limit
argument; otherwise the method will continue until it finishes counting or times out.
Arguments
Note: Global (non-ancestor) queries ignore this argument.
Returns a list of indexes used by an executed query, including primary, composite, kind, and single-property indexes.
Caution: Invoking this method on a query that has not yet been executed will raise an AssertionError
exception.
Note: This feature is not fully supported on the development server. When used with the development server, the result is either the empty list or a list containing exactly one composite index.
For example, the following code prints various information about the indexes used by a query:
# other imports ... import webapp2 from google.appengine.api import users from google.appengine.ext import db class Greeting(db.Model): author = db.StringProperty() content = db.StringProperty(multiline=True) date = db.DateTimeProperty(auto_now_add=True) class MainPage(webapp2.RequestHandler): def get(self): user = users.get_current_user() q = db.Query(Greeting) q.filter("author =", user.user_id()) q.order("-date") q.fetch(100) index_list = q.index_list() for ix in index_list: self.response.out.write("Kind: %s" % ix.kind()) self.response.out.write("<br />") self.response.out.write("Has ancestor? %s" % ix.has_ancestor()) self.response.out.write("<br />") for name, direction in ix.properties(): self.response.out.write("Property name: "+name) self.response.out.write("<br />") if direction == db.Index.DESCENDING: self.response.out.write("Sort direction: DESCENDING") else: self.response.out.write("Sort direction: ASCENDING") self.response.out.write("<br />")
This produces output like the following for each index:
Kind: Greeting Has ancestor? False Property name: author Sort direction: ASCENDING Property name: date Sort direction: DESCENDING
Returns a base64-encoded cursor string denoting the position in the query's result set following the last result retrieved. The cursor string is safe to use in HTTP GET
and POST
parameters, and can also be stored in the Datastore or Memcache. A future invocation of the same query can provide this string via the start_cursor
parameter or the with_cursor()
method to resume retrieving results from this position.
Caution: Invoking this method on a query that has not yet been executed will raise an AssertionError
exception.
Note: Not all queries are compatible with cursors; see the Datastore Queries page for more information.
Specifies the starting and (optionally) ending positions within a query's result set from which to retrieve results. The cursor strings denoting the starting and ending positions can be obtained by calling cursor()
after a previous invocation of the query. The current query must be identical to that earlier invocation, including the entity kind, property filters, ancestor filters, and sort orders.
Arguments
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-08-07 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-08-07 UTC."],[[["The `Query` class in the `google.appengine.ext.db` module is used to retrieve entities from the App Engine Datastore, allowing you to customize searches with filters, ancestor conditions, and sort orders."],["Developers are encouraged to use the NDB Client Library instead of the older DB Client Library, which is what this content refers to, due to the advantages it has such as automatic entity caching."],["You can customize `Query` objects to filter results using methods like `filter()`, `ancestor()`, and `order()`, and these can be chained together for complex queries."],["Queries can be executed using methods like `run()`, `get()`, and `fetch()`, providing options to iterate through results, retrieve a single entity, or get a list of results, respectively."],["The `Query` constructor allows for specifying various options such as `keys_only`, `cursor`, `namespace`, `projection`, and `distinct`, enabling fine-tuning of the query's behavior and returned data."]]],[]]
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4