class documentation

class QuerySet: (source)

View In Hierarchy

Represent a lazy database lookup for a set of objects.

Class Method as_manager Undocumented
Method __aiter__ Undocumented
Method __and__ Undocumented
Method __bool__ Undocumented
Method __class_getitem__ Undocumented
Method __deepcopy__ Don't populate the QuerySet's cache.
Method __getitem__ Retrieve an item or slice from the set of results.
Method __getstate__ Undocumented
Method __init__ Undocumented
Method __iter__ The queryset iterator protocol uses three nested iterators in the default case: 1. sql.compiler.execute_sql() - Returns 100 rows at time (constants.GET_ITERATOR_CHUNK_SIZE) using cursor...
Method __len__ Undocumented
Method __or__ Undocumented
Method __repr__ Undocumented
Method __setstate__ Undocumented
Method __xor__ Undocumented
Async Method aaggregate Undocumented
Async Method abulk_create Undocumented
Async Method abulk_update Undocumented
Async Method acontains Undocumented
Async Method acount Undocumented
Async Method acreate Undocumented
Async Method adelete Undocumented
Async Method aearliest Undocumented
Async Method aexists Undocumented
Async Method aexplain Undocumented
Async Method afirst Undocumented
Async Method aget Undocumented
Async Method aget_or_create Undocumented
Method aggregate Return a dictionary containing the calculations (aggregation) over the current queryset.
Async Method ain_bulk Undocumented
Async Method aiterator An asynchronous iterator over the results from applying this QuerySet to the database.
Async Method alast Undocumented
Async Method alatest Undocumented
Method alias Return a query set with added aliases for extra data or aggregations.
Method all Return a new QuerySet that is a copy of the current one. This allows a QuerySet to proxy for a model manager in some cases.
Method annotate Return a query set in which the returned objects have been annotated with extra data or aggregations.
Async Method aupdate Undocumented
Async Method aupdate_or_create Undocumented
Method bulk_create Insert each of the instances into the database. Do *not* call save() on each of the instances, do not send any pre/post_save signals, and do not set the primary key attribute if it is an autoincrement field (except if features...
Method bulk_update Update the given fields in each of the given objects in the database.
Method complex_filter Return a new QuerySet instance with filter_obj added to the filters.
Method contains Return True if the QuerySet contains the provided obj, False otherwise.
Method count Perform a SELECT COUNT() and return the number of records as an integer.
Method create Create a new object with the given kwargs, saving it to the database and returning the created object.
Method dates Return a list of date objects representing all available dates for the given field_name, scoped to 'kind'.
Method datetimes Return a list of datetime objects representing all available datetimes for the given field_name, scoped to 'kind'.
Method defer Defer the loading of data for certain fields until they are accessed. Add the set of deferred fields to any existing set of deferred fields. The only exception to this is if None is passed in as the only parameter, in which case removal all deferrals.
Method delete Delete the records in the current QuerySet.
Method difference Undocumented
Method distinct Return a new QuerySet instance that will select only distinct results.
Method earliest Undocumented
Method exclude Return a new QuerySet instance with NOT (args) ANDed to the existing set.
Method exists Return True if the QuerySet would have any results, False otherwise.
Method explain Runs an EXPLAIN on the SQL query this QuerySet would perform, and returns the results.
Method extra Add extra SQL fragments to the query.
Method filter Return a new QuerySet instance with the args ANDed to the existing set.
Method first Return the first object of a query or None if no match is found.
Method get Perform the query and return a single object matching the given keyword arguments.
Method get_or_create Look up an object with the given kwargs, creating one if necessary. Return a tuple of (object, created), where created is a boolean specifying whether an object was created.
Method in_bulk Return a dictionary mapping each of the given IDs to the object with that ID. If `id_list` isn't provided, evaluate the entire QuerySet.
Method intersection Undocumented
Method iterator An iterator over the results from applying this QuerySet to the database. chunk_size must be provided for QuerySets that prefetch related objects. Otherwise, a default chunk_size of 2000 is supplied.
Method last Return the last object of a query or None if no match is found.
Method latest Return the latest object according to fields (if given) or by the model's Meta.get_latest_by.
Method none Return an empty QuerySet.
Method only Essentially, the opposite of defer(). Only the fields passed into this method and that are not already specified as deferred are loaded immediately when the queryset is evaluated.
Method order_by Return a new QuerySet instance with the ordering changed.
Method prefetch_related Return a new QuerySet instance that will prefetch the specified Many-To-One and Many-To-Many related objects when the QuerySet is evaluated.
Method query.setter Undocumented
Method raw Undocumented
Method resolve_expression Undocumented
Method reverse Reverse the ordering of the QuerySet.
Method select_for_update Return a new QuerySet instance that will select objects with a FOR UPDATE lock.
Method select_related Return a new QuerySet instance that will select related objects.
Method union Undocumented
Method update Update all elements in the current QuerySet, setting all the given fields to the appropriate values.
Method update_or_create Look up an object with the given kwargs, updating one with defaults if it exists, otherwise create a new one. Return a tuple (object, created), where created is a boolean specifying whether an object was created.
Method using Select which database this QuerySet should execute against.
Method values Undocumented
Method values_list Undocumented
Instance Variable model Undocumented
Property db Return the database used if this query is executed now.
Property ordered Return True if the QuerySet is ordered -- i.e. has an order_by() clause or a default ordering on the model (or is empty).
Property query Undocumented
Static Method _validate_values_are_expressions Undocumented
Method _add_hints Update hinting information for use by routers. Add new key/values or overwrite existing key/values.
Method _annotate Undocumented
Method _batched_insert Helper method for bulk_create() to insert objs one batch at a time.
Method _chain Return a copy of the current QuerySet that's ready for another operation.
Method _check_bulk_create_options Undocumented
Method _check_operator_queryset Undocumented
Method _clone Return a copy of the current QuerySet. A lightweight alternative to deepcopy().
Method _combinator_query Undocumented
Method _earliest Return the earliest object according to fields (if given) or by the model's Meta.get_latest_by.
Method _extract_model_params Prepare `params` for creating a model instance based on the given kwargs; for use by get_or_create().
Method _fetch_all Undocumented
Method _filter_or_exclude Undocumented
Method _filter_or_exclude_inplace Undocumented
Method _has_filters Check if this QuerySet has any filtering going on. This isn't equivalent with checking if all objects are present in results, for example, qs[1:]._has_filters() -> False.
Method _insert Insert a new record for the given model. This provides an interface to the InsertQuery class and is how Model.save() is implemented.
Method _iterator Undocumented
Method _merge_known_related_objects Keep track of all known related objects from either QuerySet instance.
Method _merge_sanity_check Check that two QuerySet classes may be merged.
Method _next_is_sticky Indicate that the next filter call and the one following that should be treated as a single filter. This is only important when it comes to determining when to reuse tables for many-to-many filters. Required so that we can filter naturally on the results of related managers.
Method _not_support_combined_queries Undocumented
Method _prefetch_related_objects Undocumented
Method _prepare_for_bulk_create Undocumented
Method _raw_delete Delete objects found from the given queryset in single direct SQL query. No signals are sent and there is no protection for cascades.
Method _update A version of update() that accepts field objects instead of field names. Used primarily for model saving and not intended for use by general code (it requires too much poking around at model internals to be useful at that level).
Method _values Undocumented
Instance Variable _db Undocumented
Instance Variable _defer_next_filter Undocumented
Instance Variable _deferred_filter Undocumented
Instance Variable _fields Undocumented
Instance Variable _for_write Undocumented
Instance Variable _hints Undocumented
Instance Variable _iterable_class Undocumented
Instance Variable _known_related_objects Undocumented
Instance Variable _prefetch_done Undocumented
Instance Variable _prefetch_related_lookups Undocumented
Instance Variable _query Undocumented
Instance Variable _result_cache Undocumented
Instance Variable _sticky_filter Undocumented
def as_manager(cls): (source)

Undocumented

def __aiter__(self): (source)

Undocumented

def __and__(self, other): (source)

Undocumented

def __bool__(self): (source)

Undocumented

def __class_getitem__(cls, *args, **kwargs): (source)

Undocumented

def __deepcopy__(self, memo): (source)

Don't populate the QuerySet's cache.

def __getitem__(self, k): (source)

Retrieve an item or slice from the set of results.

def __getstate__(self): (source)

Undocumented

def __init__(self, model=None, query=None, using=None, hints=None): (source)

Undocumented

def __iter__(self): (source)

The queryset iterator protocol uses three nested iterators in the default case: 1. sql.compiler.execute_sql() - Returns 100 rows at time (constants.GET_ITERATOR_CHUNK_SIZE) using cursor.fetchmany(). This part is responsible for doing some column masking, and returning the rows in chunks. 2. sql.compiler.results_iter() - Returns one row at time. At this point the rows are still just tuples. In some cases the return values are converted to Python values at this location. 3. self.iterator() - Responsible for turning the rows into model objects.

def __len__(self): (source)

Undocumented

def __or__(self, other): (source)

Undocumented

def __repr__(self): (source)

Undocumented

def __setstate__(self, state): (source)

Undocumented

def __xor__(self, other): (source)

Undocumented

async def aaggregate(self, *args, **kwargs): (source)

Undocumented

async def abulk_create(self, objs, batch_size=None, ignore_conflicts=False, update_conflicts=False, update_fields=None, unique_fields=None): (source)

Undocumented

async def abulk_update(self, objs, fields, batch_size=None): (source)

Undocumented

async def acontains(self, obj): (source)

Undocumented

async def acount(self): (source)

Undocumented

async def acreate(self, **kwargs): (source)

Undocumented

async def adelete(self): (source)

Undocumented

async def aearliest(self, *fields): (source)

Undocumented

async def aexists(self): (source)

Undocumented

async def aexplain(self, *, format=None, **options): (source)

Undocumented

async def afirst(self): (source)

Undocumented

async def aget(self, *args, **kwargs): (source)

Undocumented

async def aget_or_create(self, defaults=None, **kwargs): (source)

Undocumented

def aggregate(self, *args, **kwargs): (source)

Return a dictionary containing the calculations (aggregation) over the current queryset. If args is present the expression is passed as a kwarg using the Aggregate object's default alias.

async def ain_bulk(self, id_list=None, *, field_name='pk'): (source)

Undocumented

async def aiterator(self, chunk_size=2000): (source)

An asynchronous iterator over the results from applying this QuerySet to the database.

async def alast(self): (source)

Undocumented

async def alatest(self, *fields): (source)

Undocumented

def alias(self, *args, **kwargs): (source)

Return a query set with added aliases for extra data or aggregations.

def all(self): (source)

Return a new QuerySet that is a copy of the current one. This allows a QuerySet to proxy for a model manager in some cases.

def annotate(self, *args, **kwargs): (source)

Return a query set in which the returned objects have been annotated with extra data or aggregations.

async def aupdate(self, **kwargs): (source)

Undocumented

async def aupdate_or_create(self, defaults=None, **kwargs): (source)

Undocumented

def bulk_create(self, objs, batch_size=None, ignore_conflicts=False, update_conflicts=False, update_fields=None, unique_fields=None): (source)

Insert each of the instances into the database. Do *not* call save() on each of the instances, do not send any pre/post_save signals, and do not set the primary key attribute if it is an autoincrement field (except if features.can_return_rows_from_bulk_insert=True). Multi-table models are not supported.

def bulk_update(self, objs, fields, batch_size=None): (source)

Update the given fields in each of the given objects in the database.

def complex_filter(self, filter_obj): (source)

Return a new QuerySet instance with filter_obj added to the filters. filter_obj can be a Q object or a dictionary of keyword lookup arguments. This exists to support framework features such as 'limit_choices_to', and usually it will be more natural to use other methods.

def contains(self, obj): (source)

Return True if the QuerySet contains the provided obj, False otherwise.

def count(self): (source)

Perform a SELECT COUNT() and return the number of records as an integer. If the QuerySet is already fully cached, return the length of the cached results set to avoid multiple SELECT COUNT(*) calls.

def create(self, **kwargs): (source)

Create a new object with the given kwargs, saving it to the database and returning the created object.

def dates(self, field_name, kind, order='ASC'): (source)

Return a list of date objects representing all available dates for the given field_name, scoped to 'kind'.

def datetimes(self, field_name, kind, order='ASC', tzinfo=None, is_dst=timezone.NOT_PASSED): (source)

Return a list of datetime objects representing all available datetimes for the given field_name, scoped to 'kind'.

def defer(self, *fields): (source)

Defer the loading of data for certain fields until they are accessed. Add the set of deferred fields to any existing set of deferred fields. The only exception to this is if None is passed in as the only parameter, in which case removal all deferrals.

def delete(self): (source)

Delete the records in the current QuerySet.

def difference(self, *other_qs): (source)

Undocumented

def distinct(self, *field_names): (source)

Return a new QuerySet instance that will select only distinct results.

def earliest(self, *fields): (source)

Undocumented

def exclude(self, *args, **kwargs): (source)

Return a new QuerySet instance with NOT (args) ANDed to the existing set.

def exists(self): (source)

Return True if the QuerySet would have any results, False otherwise.

def explain(self, *, format=None, **options): (source)

Runs an EXPLAIN on the SQL query this QuerySet would perform, and returns the results.

def extra(self, select=None, where=None, params=None, tables=None, order_by=None, select_params=None): (source)

Add extra SQL fragments to the query.

def filter(self, *args, **kwargs): (source)

Return a new QuerySet instance with the args ANDed to the existing set.

def first(self): (source)

Return the first object of a query or None if no match is found.

def get(self, *args, **kwargs): (source)

Perform the query and return a single object matching the given keyword arguments.

def get_or_create(self, defaults=None, **kwargs): (source)

Look up an object with the given kwargs, creating one if necessary. Return a tuple of (object, created), where created is a boolean specifying whether an object was created.

def in_bulk(self, id_list=None, *, field_name='pk'): (source)

Return a dictionary mapping each of the given IDs to the object with that ID. If `id_list` isn't provided, evaluate the entire QuerySet.

def intersection(self, *other_qs): (source)

Undocumented

def iterator(self, chunk_size=None): (source)

An iterator over the results from applying this QuerySet to the database. chunk_size must be provided for QuerySets that prefetch related objects. Otherwise, a default chunk_size of 2000 is supplied.

def last(self): (source)

Return the last object of a query or None if no match is found.

def latest(self, *fields): (source)

Return the latest object according to fields (if given) or by the model's Meta.get_latest_by.

def none(self): (source)

Return an empty QuerySet.

def only(self, *fields): (source)

Essentially, the opposite of defer(). Only the fields passed into this method and that are not already specified as deferred are loaded immediately when the queryset is evaluated.

def order_by(self, *field_names): (source)

Return a new QuerySet instance with the ordering changed.

def prefetch_related(self, *lookups): (source)

Return a new QuerySet instance that will prefetch the specified Many-To-One and Many-To-Many related objects when the QuerySet is evaluated. When prefetch_related() is called more than once, append to the list of prefetch lookups. If prefetch_related(None) is called, clear the list.

@query.setter
def query(self, value): (source)

Undocumented

def raw(self, raw_query, params=(), translations=None, using=None): (source)

Undocumented

def resolve_expression(self, *args, **kwargs): (source)

Undocumented

def reverse(self): (source)

Reverse the ordering of the QuerySet.

def select_for_update(self, nowait=False, skip_locked=False, of=(), no_key=False): (source)

Return a new QuerySet instance that will select objects with a FOR UPDATE lock.

def select_related(self, *fields): (source)

Return a new QuerySet instance that will select related objects. If fields are specified, they must be ForeignKey fields and only those related objects are included in the selection. If select_related(None) is called, clear the list.

def union(self, *other_qs, all=False): (source)

Undocumented

def update(self, **kwargs): (source)

Update all elements in the current QuerySet, setting all the given fields to the appropriate values.

def update_or_create(self, defaults=None, **kwargs): (source)

Look up an object with the given kwargs, updating one with defaults if it exists, otherwise create a new one. Return a tuple (object, created), where created is a boolean specifying whether an object was created.

def using(self, alias): (source)

Select which database this QuerySet should execute against.

def values(self, *fields, **expressions): (source)

Undocumented

def values_list(self, *fields, flat=False, named=False): (source)

Undocumented

Undocumented

Return the database used if this query is executed now.

Return True if the QuerySet is ordered -- i.e. has an order_by() clause or a default ordering on the model (or is empty).

Undocumented

@staticmethod
def _validate_values_are_expressions(values, method_name): (source)

Undocumented

def _add_hints(self, **hints): (source)

Update hinting information for use by routers. Add new key/values or overwrite existing key/values.

def _annotate(self, args, kwargs, select=True): (source)

Undocumented

def _batched_insert(self, objs, fields, batch_size, on_conflict=None, update_fields=None, unique_fields=None): (source)

Helper method for bulk_create() to insert objs one batch at a time.

def _chain(self): (source)

Return a copy of the current QuerySet that's ready for another operation.

def _check_bulk_create_options(self, ignore_conflicts, update_conflicts, update_fields, unique_fields): (source)

Undocumented

def _check_operator_queryset(self, other, operator_): (source)

Undocumented

def _clone(self): (source)

Return a copy of the current QuerySet. A lightweight alternative to deepcopy().

def _combinator_query(self, combinator, *other_qs, all=False): (source)

Undocumented

def _earliest(self, *fields): (source)

Return the earliest object according to fields (if given) or by the model's Meta.get_latest_by.

def _extract_model_params(self, defaults, **kwargs): (source)

Prepare `params` for creating a model instance based on the given kwargs; for use by get_or_create().

def _fetch_all(self): (source)

Undocumented

def _filter_or_exclude(self, negate, args, kwargs): (source)

Undocumented

def _filter_or_exclude_inplace(self, negate, args, kwargs): (source)

Undocumented

def _has_filters(self): (source)

Check if this QuerySet has any filtering going on. This isn't equivalent with checking if all objects are present in results, for example, qs[1:]._has_filters() -> False.

def _insert(self, objs, fields, returning_fields=None, raw=False, using=None, on_conflict=None, update_fields=None, unique_fields=None): (source)

Insert a new record for the given model. This provides an interface to the InsertQuery class and is how Model.save() is implemented.

def _iterator(self, use_chunked_fetch, chunk_size): (source)

Undocumented

def _merge_known_related_objects(self, other): (source)

Keep track of all known related objects from either QuerySet instance.

def _merge_sanity_check(self, other): (source)

Check that two QuerySet classes may be merged.

def _next_is_sticky(self): (source)

Indicate that the next filter call and the one following that should be treated as a single filter. This is only important when it comes to determining when to reuse tables for many-to-many filters. Required so that we can filter naturally on the results of related managers. This doesn't return a clone of the current QuerySet (it returns "self"). The method is only used internally and should be immediately followed by a filter() that does create a clone.

def _not_support_combined_queries(self, operation_name): (source)

Undocumented

def _prefetch_related_objects(self): (source)

Undocumented

def _prepare_for_bulk_create(self, objs): (source)

Undocumented

def _raw_delete(self, using): (source)

Delete objects found from the given queryset in single direct SQL query. No signals are sent and there is no protection for cascades.

def _update(self, values): (source)

A version of update() that accepts field objects instead of field names. Used primarily for model saving and not intended for use by general code (it requires too much poking around at model internals to be useful at that level).

def _values(self, *fields, **expressions): (source)

Undocumented

Undocumented

_defer_next_filter: bool = (source)

Undocumented

_deferred_filter = (source)

Undocumented

Undocumented

_for_write: bool = (source)

Undocumented

Undocumented

_iterable_class = (source)

Undocumented

_known_related_objects: dict = (source)

Undocumented

_prefetch_done: bool = (source)

Undocumented

_prefetch_related_lookups: tuple = (source)

Undocumented

Undocumented

_result_cache = (source)

Undocumented

_sticky_filter: bool = (source)

Undocumented