Python 2.7 has reached end of support
and will bedeprecatedon 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 theirdeprecation date. We recommend that
youmigrate to the latest supported version of Python.
Stay organized with collectionsSave and categorize content based on your preferences.
AQueryobject represents an NDB query, a request for
a filtered, sorted list of entities.
This page contains reference documentation. For a general discussion
of NDB queries, seeQueries.
Query Options
Many query methods take a standard set of additional
options, either in the form of keyword arguments such askeys_only=True, or asQueryOptionsobject passed withoptions=QueryOptions(...).
Queries support a variety of configuration options.
These are specified by keyword arguments to theQuerymethods:
Argument
Type
Default
Description
keys_only
bool
False
All operations return keys instead of entities.
projection
tuple (or list) of properties (or strings)
None
Operations return entities with only the specified properties
set.projection=[Article.title, Article.date]orprojection=['title', 'date']fetches entities with just those two fields set.
(SeeProjection Queries.)
offset
int
0
Number of query results to skip.
limit
int
No limit
Maximum number of query results to return.
batch_size
int
20
Batch size.
Affects efficiency of queries only; larger batch sizes use more memory but make fewer RPC calls.
Overrides RPC deadline (which defaults to 5 seconds if not overridden whenContextcreated)
read_policy
ndb.EVENTUAL_CONSISTENCY
The read policy. Set tondb.EVENTUAL_CONSISTENCYto get
perhaps-quicker results without waiting for the Datastore to
apply pending changes to all returned records.
To run a query with a specific set of options,
pass the keyword arguments to the applicable method:
qry=Employee.query().filter(...).order(...)# Create a queryforacctinqry.fetch(10,offset=20):# Skip the first 20printacct
Occasionally, you might want to keep a set of query options
around and use them in various places. While you could just
keep them in a dictionary and pass this dictionary to the
methods using**kwds, you can also create aQueryOptionsobject and pass
it using the options keyword argument.
The following two examples are equivalent:
Typically, an application creates aQueryby callingModel.query(). But it's also possible to callndb.Query().
Arguments
kind
Optional kind string. Normally, the name of a entity class.
ancestor
Optional ancestor Key.
filters
Optional Node representing a filter expression tree.
orders
Optionaldatastore_query.Orderobject.
app
Optional app id.
namespace
Optional namespace. If not specified,
the default namespace at the time the query is executed will be used.
projection
Optional list or tuple of properties to project.
group_by
Optional list or tuple of properties to group by.
default_options
OptionalQueryOptionsobject
giving default query options to be used when the query is executed.
Instance Methods
filter(filter1, filter2, ...)
Returns a newQuerywith additional filter(s) applied.
Takes filter arguments as described inQueries.qry.filter(filter1).filter(filter2)is equivalent toqry.filter(filter1, filter2)
get(**q_options)
Returns the first query result, if any (otherwiseNone).
This is similar to callingq.fetch(1)and returning
the first item of the list of results.
Returns a newQuerywith additional sort order(s) applied.
Takes one or more arguments which are properties or "negated" properties.
For example, to sort users by age and "break ties" by name, you might
use something likeqry.order(-Account.birthday, Account.name)
bind(...values...)
This function is for use with GQL queries that use parameter
bindings (:1,:2, etc.) or named bindings
(:foo,:bar, etc.). It binds the passed
values to the parameters.
To bind parameters, you might call something likeqry.bind("USA", 49).
To bind named parameters, you might call something likeqry.bind(region = "USA", threshold = 49).
Returns a newQueryobject with the parameter values bound.
count(limit=None,**q_options)
Returns the number of query results, up to a limit.
This returns the same result aslen(q.fetch(limit))but more
efficiently.
Asynchronously counts the number of query results, up to a limit;
it returns aFuturewhose result is a number.
This is the asynchronous version ofcount().
Asynchronously fetch a list of query results, up to a limit.
Returns aFuturewhose result is a list of results.
This is the asynchronous version offetch().
fetch_page(page_size,**q_options)
Fetch a "page" of results. This is a specialized method for
use by paging user interfaces.
cursoraquery cursorpointing
to the "next" batch of results. If there are no more results, this might
beNone.
moreboolindicating whether there are (likely)
more results after this batch.
IfFalse, there are no more results;
ifTrue, there areprobablymore results.
To fetch the next page,
pass the cursor returned by one call to the next call usingstart_cursor=cursor.
A common idiom is to pass the cursor to
the client usingcursor.urlsafe()and to reconstruct that cursor on a subsequent request usingCursor(urlsafe=string).
fetch_page_async(page_size,**q_options)
Asynchronously fetch a "page" of results. This is the asynchronous version
offetch_page().
get_async(**q_options)
Asynchronously returns the first query result, if any
(otherwiseNone). This is the asynchronous version
ofget().
iter(**q_options)
Constructs and returns an iterator over the query.
Callback signatureThe callback is normally called with an entity
as argument. However, ifkeys_only=Trueis given, it is called
with aKey.
Ifpass_batch_into_callback=Trueis given, the callback is
called with three arguments: the current batch, the index within
the batch, and the entity orKeyat that index.
The callback can
return whatever it wants. If the callback isNone, a trivial
callback is assumed that just returns the entity or key passed in.
Optionalmerge_futureThemerge_futureis an advanced argument
that can be used to override how the callback results are combined
into the overallmap()return value. By default, a list of
callback return values is produced. By substituting one of a
small number of specialized alternatives you can arrange
otherwise. See the source code fortasklets.MultiFuturefor the default
implementation and a description of
the protocol themerge_futureobject must implement. Alternatives from the same
module includeQueueFuture,SerialQueueFutureandReducingFuture.
Returns a list of the results of all the callbacks.
(But see 'optionalmerge_future' above.) It returns
when the query has run to completion and all callbacks have returned.
[[["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-09-03 UTC."],[[["\u003cp\u003eThis documentation covers how to use NDB queries within the legacy App Engine standard environment's first-generation runtimes, noting that for App Engine Python 3, a migration guide is recommended.\u003c/p\u003e\n"],["\u003cp\u003eAn NDB \u003ccode\u003eQuery\u003c/code\u003e object is used to request a filtered and sorted list of entities, and you can create one using the \u003ccode\u003e<var>Model</var>.query()\u003c/code\u003e method or directly using \u003ccode\u003endb.Query()\u003c/code\u003e.\u003c/p\u003e\n"],["\u003cp\u003eQueries can be configured using various keyword arguments or a \u003ccode\u003eQueryOptions\u003c/code\u003e object, allowing for customizations such as returning only keys (\u003ccode\u003ekeys_only\u003c/code\u003e), limiting results (\u003ccode\u003elimit\u003c/code\u003e), skipping results (\u003ccode\u003eoffset\u003c/code\u003e), or specifying a data projection (\u003ccode\u003eprojection\u003c/code\u003e).\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003eQuery\u003c/code\u003e object has several instance methods like \u003ccode\u003efilter()\u003c/code\u003e, \u003ccode\u003eorder()\u003c/code\u003e, \u003ccode\u003eget()\u003c/code\u003e, \u003ccode\u003ecount()\u003c/code\u003e, \u003ccode\u003efetch()\u003c/code\u003e, \u003ccode\u003efetch_page()\u003c/code\u003e, \u003ccode\u003emap()\u003c/code\u003e and their async versions, allowing for advanced query customization, execution, and data retrieval.\u003c/p\u003e\n"],["\u003cp\u003eQuery methods often accept keyword arguments, such as \u003ccode\u003elimit\u003c/code\u003e, \u003ccode\u003eoffset\u003c/code\u003e, \u003ccode\u003ekeys_only\u003c/code\u003e, and \u003ccode\u003eprojection\u003c/code\u003e, to refine the results, and these same options can be used in a \u003ccode\u003eQueryOptions\u003c/code\u003e object.\u003c/p\u003e\n"]]],[],null,["# NDB Query Class\n\n| This page describes how to use the legacy bundled services and APIs. This API can only run in first-generation runtimes in the App Engine standard environment. If you are updating to the App Engine Python 3 runtime, refer to the [migration guide](/appengine/migration-center/standard/migrate-to-second-gen/python-differences) to learn about your migration options for legacy bundled services.\n\nA `Query` object represents an NDB query, a request for\na filtered, sorted list of entities.\n\nThis page contains reference documentation. For a general discussion\nof NDB queries, see [Queries](/appengine/docs/legacy/standard/python/ndb/queries).\n\nQuery Options\n-------------\n\nMany query methods take a standard set of additional\noptions, either in the form of keyword arguments such as\n`keys_only=True`, or as\n`QueryOptions` object passed with\n`options=QueryOptions(...)`.\n\nQueries support a variety of configuration options.\nThese are specified by keyword arguments to the `Query` methods:\n\nTo run a query with a specific set of options,\npass the keyword arguments to the applicable method:\n\n```python\nqry = Employee.query().filter(...).order(...) # Create a query\nfor acct in qry.fetch(10, offset=20): # Skip the first 20\n print acct\n```\n\nOccasionally, you might want to keep a set of query options\naround and use them in various places. While you could just\nkeep them in a dictionary and pass this dictionary to the\nmethods using `**kwds`, you can also create a\n`QueryOptions` object and pass\nit using the options keyword argument.\nThe following two examples are equivalent:\n\n```python\nqo = ndb.QueryOptions(keys_only=True, offset=20)\nresults = qry.fetch(10, options=qo)\nresults = qry.fetch(10, keys_only=True, offset=20)\n```\n\nConstructor\n-----------\n\nTypically, an application creates a `Query` by calling\n\u003cvar translate=\"no\"\u003eModel\u003c/var\u003e`.query()`. But it's also possible to call\n`ndb.Query()`.\n\n**Arguments**\n\nkind\n: Optional kind string. Normally, the name of a entity class.\n\nancestor\n: Optional ancestor Key.\n\nfilters\n: Optional Node representing a filter expression tree.\n\norders\n: Optional `datastore_query.Order` object.\n\napp\n: Optional app id.\n\nnamespace\n: Optional namespace. If not specified,\n the default namespace at the time the query is executed will be used.\n\nprojection\n: Optional list or tuple of properties to project.\n\ngroup_by\n: Optional list or tuple of properties to group by.\n\ndefault_options\n: Optional\n [QueryOptions](/appengine/docs/legacy/standard/python/ndb/queryclass#kwdargs_options) object\n giving default query options to be used when the query is executed.\n\nInstance Methods\n----------------\n\nfilter(\u003cvar translate=\"no\"\u003efilter1, filter2, ...\u003c/var\u003e)\n: Returns a new `Query` with additional filter(s) applied.\n Takes filter arguments as described in\n [Queries](/appengine/docs/legacy/standard/python/ndb/queries).\n `qry.filter(`\u003cvar translate=\"no\"\u003efilter1\u003c/var\u003e`).filter(`\u003cvar translate=\"no\"\u003efilter2\u003c/var\u003e`)`\n is equivalent to\n `qry.filter(`\u003cvar translate=\"no\"\u003efilter1\u003c/var\u003e`, `\u003cvar translate=\"no\"\u003efilter2\u003c/var\u003e`)`\n\nget(\\*\\*q_options)\n: Returns the first query result, if any (otherwise `None`).\n This is similar to calling `q.fetch(1)` and returning\n the first item of the list of results.\n\n **Arguments**\n\n \\*\\*q_options\n : All [query options keyword arguments](#kwdargs_options)\n are supported.\n\norder(\u003cvar translate=\"no\"\u003eorder1\u003c/var\u003e, \u003cvar translate=\"no\"\u003eorder2\u003c/var\u003e, ...)\n: Returns a new `Query` with additional sort order(s) applied.\n Takes one or more arguments which are properties or \"negated\" properties.\n For example, to sort users by age and \"break ties\" by name, you might\n use something like `qry.order(-Account.birthday, Account.name)`\n\nbind(\u003cvar translate=\"no\"\u003e...values...\u003c/var\u003e)\n: This function is for use with GQL queries that use parameter\n bindings (`:1`, `:2`, etc.) or named bindings\n (`:foo`, `:bar`, etc.). It binds the passed\n values to the parameters.\n\n To bind parameters, you might call something like\n `qry.bind(\"USA\", 49)`.\n To bind named parameters, you might call something like\n `qry.bind(region = \"USA\", threshold = 49)`.\n\n Returns a new `Query` object with the parameter values bound.\n\ncount(limit=None, \\*\\*q_options)\n: Returns the number of query results, up to a limit.\n This returns the same result as `len(q.fetch(limit))` but more\n efficiently.\n\n **Arguments**\n\n limit\n : How many results to count at most\n\n \\*\\*q_options\n : All [query options keyword arguments](#kwdargs_options)\n and [context options](/appengine/docs/legacy/standard/python/ndb/functions#context_options)\n are supported.\n\ncount_async(limit, \\*\\*q_options)\n: Asynchronously counts the number of query results, up to a limit;\n it returns a [Future](/appengine/docs/legacy/standard/python/ndb/futureclass)\n whose result is a number.\n This is the asynchronous version of [count()](#Query_count).\n\nfetch(limit, \\*\\*q_options)\n\n: Fetch a list of query results, up to a limit. **Arguments**\n\n limit\n : How many results to count at most\n\n \\*\\*q_options\n : All [query options keyword arguments](#kwdargs_options)\n are supported.\n\nfetch_async(limit, \\*\\*q_options)\n: Asynchronously fetch a list of query results, up to a limit.\n Returns a [Future](/appengine/docs/legacy/standard/python/ndb/futureclass)\n whose result is a list of results.\n This is the asynchronous version of [fetch()](#Query_fetch).\n\nfetch_page(page_size, \\*\\*q_options)\n\n: Fetch a \"page\" of results. This is a specialized method for use by paging user interfaces. **Arguments**\n\n page_size\n : At most this many results will be returned.\n\n \\*\\*q_options\n : All [query options keyword arguments](#kwdargs_options)\n are supported.\n\n Returns a tuple `(`\u003cvar translate=\"no\"\u003eresults\u003c/var\u003e`,\n `\u003cvar translate=\"no\"\u003ecursor\u003c/var\u003e`, `\u003cvar translate=\"no\"\u003emore\u003c/var\u003e`)`:\n\n - \u003cvar translate=\"no\"\u003eresults\u003c/var\u003e list of query results\n - \u003cvar translate=\"no\"\u003ecursor\u003c/var\u003e a [query cursor](/appengine/docs/legacy/standard/python/ndb/queries#cursors) pointing to the \"next\" batch of results. If there are no more results, this might be `None`.\n - \u003cvar translate=\"no\"\u003emore\u003c/var\u003e `bool` indicating whether there are (likely) more results after this batch. If `False`, there are no more results; if `True`, there are *probably* more results.\n\n To fetch the next page,\n pass the cursor returned by one call to the next call using\n `start_cursor=`\u003cvar translate=\"no\"\u003ecursor\u003c/var\u003e.\n A common idiom is to pass the cursor to\n the client using \u003cvar translate=\"no\"\u003ecursor\u003c/var\u003e`.urlsafe()`\n and to reconstruct that cursor on a subsequent request using\n `Cursor(urlsafe=`\u003cvar translate=\"no\"\u003estring\u003c/var\u003e`)`.\n\nfetch_page_async(page_size, \\*\\*q_options)\n: Asynchronously fetch a \"page\" of results. This is the asynchronous version\n of [fetch_page()](#Query_fetch_page).\n\nget_async(\\*\\*q_options)\n: Asynchronously returns the first query result, if any\n (otherwise `None`). This is the asynchronous version\n of [get()](#Query_get).\n\niter(\\*\\*q_options)\n\n: Constructs and returns an iterator over the query. **Arguments**\n\n \\*\\*q_options\n : All [query options keyword arguments](#kwdargs_options)\n are supported.\n\n Returns a [QueryIterator](/appengine/docs/legacy/standard/python/ndb/queries#iterators) object.\n\nmap(callback, pass_batch_into_callback=None, merge_future=None, \\*\\*q_options)\n\n: Map a callback function or tasklet over the query results. That is, apply the function (or tasklet) to each entity in the query results. **Arguments**\n\n callback\n : A function or tasklet to be applied to each result.\n\n pass_batch_into_callback\n : If `True`, calls the callback with batch information\n arguments as described below.\n\n merge_future\n : Optional [Future](/appengine/docs/legacy/standard/python/ndb/futureclass) subclass;\n see below.\n\n \\*\\*q_options\n : All [query options keyword arguments](#kwdargs_options)\n are supported.\n\n *Callback signature* The callback is normally called with an entity\n as argument. However, if\n `keys_only=True` is given, it is called\n with a [Key](/appengine/docs/legacy/standard/python/ndb/keyclass).\n If `pass_batch_into_callback=True` is given, the callback is\n called with three arguments: the current batch, the index within\n the batch, and the entity or `Key` at that index.\n The callback can\n return whatever it wants. If the callback is `None`, a trivial\n callback is assumed that just returns the entity or key passed in.\n\n *Optional `merge_future`* The `merge_future`\n is an advanced argument\n that can be used to override how the callback results are combined\n into the overall `map()` return value. By default, a list of\n callback return values is produced. By substituting one of a\n small number of specialized alternatives you can arrange\n otherwise. See the source code for\n `tasklets.MultiFuture` for the default\n implementation and a description of\n the protocol the `merge_future`\n object must implement. Alternatives from the same\n module include `QueueFuture`, `SerialQueueFuture`\n and `ReducingFuture`.\n\n Returns a list of the results of all the callbacks.\n (But see 'optional `merge_future`' above.) It returns\n when the query has run to completion and all callbacks have returned.\n\nmap_async(callback, pass_batch_into_callback=None, merge_future=None, \\*\\*q_options)\n: Asynchronously map a callback function or tasklet over the query results.\n This is the asynchronous version of [map()](#map)."]]