Python 2.7 ha raggiunto la fine del supporto
e verrà ritirato
il 31 gennaio 2026. Dopo il ritiro, non potrai eseguire il deployment di applicazioni Python 2.7, anche se la tua organizzazione ha utilizzato in precedenza un criterio dell'organizzazione per riattivare i deployment di runtime legacy. Le tue applicazioni Python 2.7 esistenti continueranno a essere eseguite e a ricevere traffico dopo la
data di ritiro. Ti consigliamo di eseguire la migrazione all'ultima versione supportata di Python.
Mantieni tutto organizzato con le raccolte
Salva e classifica i contenuti in base alle tue preferenze.
Un oggetto Query rappresenta una query NDB, ovvero una richiesta di un elenco filtrato e ordinato di entità.
Questa pagina contiene la documentazione di riferimento. Per una discussione generale
sulle query NDB, consulta Query.
Opzioni query
Molti metodi di query accettano un insieme standard di opzioni aggiuntive, sotto forma di argomenti della parola chiave come keys_only=True o come oggetto QueryOptions passato con options=QueryOptions(...).
Le query supportano una serie di opzioni di configurazione.
Questi vengono specificati dagli argomenti delle parole chiave per i metodi Query:
Argomento
Tipo
Predefinito
Descrizione
keys_only
bool
False
Tutte le operazioni restituiscono chiavi anziché entità.
proiezione
tupla (o elenco) di proprietà (o stringhe)
None
Le operazioni restituiscono entità con solo le proprietà specificate impostate.
projection=[Article.title, Article.date]
o projection=['title', 'date']
recupera le entità con solo questi due campi impostati.
(Consulta la sezione Query di proiezione.)
compensazione
int
0
Numero di risultati della query da saltare.
limite
int
Nessun limite
Numero massimo di risultati della query da restituire.
batch_size
int
20
Dimensione del batch.
Influisce solo sull'efficienza delle query; i batch di dimensioni maggiori utilizzano più memoria, ma eseguono meno chiamate RPC.
prefetch_size
int
None
Sostituisce la dimensione del batch per il primo batch restituito.
Sostituisce la scadenza RPC (che per impostazione predefinita è di 5 secondi se non sostituita al momento della creazione di Context)
read_policy
ndb.EVENTUAL_CONSISTENCY
Il criterio di lettura. Imposta su ndb.EVENTUAL_CONSISTENCY per ottenere risultati forse più rapidi senza attendere che Datastore applichi le modifiche in attesa a tutti i record restituiti.
Per eseguire una query con un insieme specifico di opzioni,
trasmetti gli argomenti della parola chiave al metodo applicabile:
qry=Employee.query().filter(...).order(...)# Create a queryforacctinqry.fetch(10,offset=20):# Skip the first 20printacct
A volte, potresti voler conservare un insieme di opzioni di query
e utilizzarle in vari punti. Anche se potresti semplicemente conservarli in un dizionario e passarlo ai metodi utilizzando **kwds, puoi anche creare un oggetto QueryOptions e passarlo utilizzando l'argomento della parola chiave options.
I seguenti due esempi sono equivalenti:
In genere, un'applicazione crea un Query chiamando
Model.query(). È però possibile chiamare anche
ndb.Query().
Argomenti
kind
Stringa tipo facoltativa. Di solito, il nome di una classe di entità.
antenato
Chiave antenato facoltativa.
filtri
Nodo facoltativo che rappresenta un albero di espressioni di filtro.
orders
Oggetto
datastore_query.Order facoltativo.
app
ID app facoltativo.
namespace
Spazio dei nomi facoltativo. Se non specificato, verrà utilizzato lo spazio dei nomi predefinito al momento dell'esecuzione della query.
proiezione
Elenco facoltativo o tupla di proprietà da proiettare.
group_by
Elenco o tupla facoltativi di proprietà per il raggruppamento.
default_options
Oggetto facoltativo
QueryOptions che fornisce le opzioni di query predefinite da utilizzare quando viene eseguita la query.
Metodi istanza
filter(filter1, filter2, ...)
Restituisce un nuovo Query con uno o più filtri aggiuntivi applicati.
Accetta gli argomenti del filtro come descritto in
Query.
qry.filter(filter1).filter(filter2)
è equivalente a
qry.filter(filter1, filter2)
get(**q_options)
Restituisce il primo risultato della query, se esistente (in caso contrario None).
È simile a chiamare q.fetch(1) e restituire
il primo elemento dell'elenco dei risultati.
Restituisce un nuovo Query con un ordine di ordinamento aggiuntivo o più.
Accetta uno o più argomenti che sono proprietà o proprietà "negate".
Ad esempio, per ordinare gli utenti per età e "risolvere i casi in cui più utenti hanno lo stesso valore" in base al nome, potresti
utilizzare qualcosa di simile a qry.order(-Account.birthday, Account.name)
bind(...values...)
Questa funzione è da utilizzare con le query GQL che utilizzano associazioni di parametri (:1, :2 e così via) o associazioni denominate (:foo, :bar e così via). Collega i valori passati ai parametri.
Per associare i parametri, potresti chiamare qualcosa come
qry.bind("USA", 49).
Per associare i parametri denominati, potresti chiamare qualcosa come
qry.bind(region = "USA", threshold = 49).
Restituisce un nuovo oggetto Query con i valori dei parametri legati.
count(limit=None, **q_options)
Restituisce il numero di risultati della query, fino a un limite.
Restituisce lo stesso risultato di len(q.fetch(limit)), ma in modo più
efficiente.
Conteggia in modo asincrono il numero di risultati della query, fino a un limite;
restituisce un Future
il cui risultato è un numero.
Questa è la versione asincrona di count().
fetch(limit, **q_options)
Recupero di un elenco di risultati di query, fino a un limite.
Recupero in modo asincrono di un elenco di risultati di query, fino a un limite.
Restituisce un Future
il cui risultato è un elenco di risultati.
Questa è la versione asincrona di fetch().
fetch_page(page_size, **q_options)
Recupero una "pagina" di risultati. Si tratta di un metodo specializzato per l'uso da parte di interfacce utente con paginazione.
Argomenti
page_size
Al massimo verranno restituiti questo numero di risultati.
cursor un cursor di query che rimanda al "batch successivo" di risultati. Se non ci sono altri risultati, potrebbe essere None.
morebool che indica se sono (probabilmente)
presenti altri risultati dopo questo batch.
Se False, non ci sono altri risultati;
se True, probabilmente ci sono altri risultati.
Per recuperare la pagina successiva,
passa il cursore restituito da una chiamata alla chiamata successiva utilizzando
start_cursor=cursor.
Un'espressione idiomatica comune è passare il cursore al
client utilizzando cursor.urlsafe()
e ricostruirlo in una richiesta successiva utilizzando
Cursor(urlsafe=string).
fetch_page_async(page_size, **q_options)
Recupero in modo asincrono di una "pagina" di risultati. Questa è la versione asincrona di fetch_page().
get_async(**q_options)
Restituisce in modo asincrono il primo risultato della query, se esistente
(in caso contrario None). Questa è la versione asincrona di
get().
iter(**q_options)
Costruisce e restituisce un iteratore per la query.
Mappa una funzione di callback o un tasklet sui risultati della query. In altre parole,
applica la funzione (o il tasklet) a ogni entità nei risultati della query.
Argomenti
callback
Una funzione o un tasklet da applicare a ogni risultato.
pass_batch_into_callback
Se True, chiama il callback con gli argomenti
delle informazioni sul batch come descritto di seguito.
merge_future
Classe secondaria Future facoltativa;
vedi di seguito.
Firma del callback Il callback viene chiamato in genere con un'entità come argomento. Tuttavia, se viene fornito keys_only=True, viene chiamato con una chiave.
Se viene specificato pass_batch_into_callback=True, il callback viene chiamato con tre argomenti: il batch corrente, l'indice all'interno del batch e l'entità o Key in quell'indice.
Il callback può
restituire ciò che vuole. Se il callback è None, viene assunto un callback banale che restituisce solo l'entità o la chiave passata.
Facoltativo merge_futuremerge_future
è un argomento avanzato
che può essere utilizzato per sostituire il modo in cui i risultati del callback vengono combinati
nel valore restituito complessivo di map(). Per impostazione predefinita, viene prodotto un elenco di valori di ritorno del callback. Sostituendo uno di un
piccolo numero di alternative specializzate, puoi organizzare
diversamente. Consulta il codice sorgente di tasklets.MultiFuture per l'implementazione predefinita e una descrizione del protocollo che l'oggetto merge_future deve implementare. Le alternative dello stesso
modulo includono QueueFuture, SerialQueueFuture
e ReducingFuture.
Restituisce un elenco dei risultati di tutti i richiami.
(ma vedi "facoltativo merge_future" sopra). Restituisce un valore quando la query è stata completata e tutti i callback sono stati restituiti.
[[["Facile da capire","easyToUnderstand","thumb-up"],["Il problema è stato risolto","solvedMyProblem","thumb-up"],["Altra","otherUp","thumb-up"]],[["Difficile da capire","hardToUnderstand","thumb-down"],["Informazioni o codice di esempio errati","incorrectInformationOrSampleCode","thumb-down"],["Mancano le informazioni o gli esempi di cui ho bisogno","missingTheInformationSamplesINeed","thumb-down"],["Problema di traduzione","translationIssue","thumb-down"],["Altra","otherDown","thumb-down"]],["Ultimo aggiornamento 2025-09-04 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)."]]