class documentation

class QuerySet:

View In Hierarchy

Represent a lazy database lookup for a set of objects.
Class Method as​_manager Undocumented
Method aggregate Return a dictionary containing the calculations (aggregation) over the current queryset.
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.
Method bulk​_create No summary
Method bulk​_update Update the given fields in each of the given objects in the database.
Method contains Return True if the queryset contains an object.
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 No summary
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 Undocumented
Method explain Undocumented
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.
Method last Return the last object of a query or None if no match is found.
Method latest Undocumented
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 raw 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 No summary
Method using Select which database this QuerySet should execute against.
Method values Undocumented
Method values​_list Undocumented
Static Method ​_validate​_values​_are​_expressions 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__ No summary
Method __len__ Undocumented
Method __or__ Undocumented
Method __repr__ Undocumented
Method __setstate__ 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 ​_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 No summary
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 No summary
Method ​_values Undocumented
Method complex​_filter Return a new QuerySet instance with filter_obj added to the filters.
Method query.setter Undocumented
Method resolve​_expression 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
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
def as_manager(cls):

Undocumented

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

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.

def alias(self, *args, **kwargs):
Return a query set with added aliases for extra data or aggregations.
def all(self):
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):
Return a query set in which the returned objects have been annotated with extra data or aggregations.
def bulk_create(self, objs, batch_size=None, ignore_conflicts=False):
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):
Update the given fields in each of the given objects in the database.
def contains(self, obj):
Return True if the queryset contains an object.
def count(self):

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):
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'):
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):
Return a list of datetime objects representing all available datetimes for the given field_name, scoped to 'kind'.
def defer(self, *fields):
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):
Delete the records in the current QuerySet.
def difference(self, *other_qs):

Undocumented

def distinct(self, *field_names):
Return a new QuerySet instance that will select only distinct results.
def earliest(self, *fields):

Undocumented

def exclude(self, *args, **kwargs):
Return a new QuerySet instance with NOT (args) ANDed to the existing set.
def exists(self):

Undocumented

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

Undocumented

def extra(self, select=None, where=None, params=None, tables=None, order_by=None, select_params=None):
Add extra SQL fragments to the query.
def filter(self, *args, **kwargs):
Return a new QuerySet instance with the args ANDed to the existing set.
def first(self):
Return the first object of a query or None if no match is found.
def get(self, *args, **kwargs):
Perform the query and return a single object matching the given keyword arguments.
def get_or_create(self, defaults=None, **kwargs):
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'):
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):

Undocumented

def iterator(self, chunk_size=2000):
An iterator over the results from applying this QuerySet to the database.
def last(self):
Return the last object of a query or None if no match is found.
def latest(self, *fields):

Undocumented

def none(self):
Return an empty QuerySet.
def only(self, *fields):
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):
Return a new QuerySet instance with the ordering changed.
def prefetch_related(self, *lookups):

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.

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

Undocumented

def reverse(self):
Reverse the ordering of the QuerySet.
def select_for_update(self, nowait=False, skip_locked=False, of=(), no_key=False):
Return a new QuerySet instance that will select objects with a FOR UPDATE lock.
def select_related(self, *fields):

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):

Undocumented

def update(self, **kwargs):
Update all elements in the current QuerySet, setting all the given fields to the appropriate values.
def update_or_create(self, defaults=None, **kwargs):
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):
Select which database this QuerySet should execute against.
def values(self, *fields, **expressions):

Undocumented

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

Undocumented

@staticmethod
def _validate_values_are_expressions(values, method_name):

Undocumented

def __and__(self, other):

Undocumented

def __bool__(self):

Undocumented

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

Undocumented

def __deepcopy__(self, memo):
Don't populate the QuerySet's cache.
def __getitem__(self, k):
Retrieve an item or slice from the set of results.
def __getstate__(self):

Undocumented

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

Undocumented

def __iter__(self):

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):

Undocumented

def __or__(self, other):

Undocumented

def __repr__(self):

Undocumented

def __setstate__(self, state):

Undocumented

def _add_hints(self, **hints):
Update hinting information for use by routers. Add new key/values or overwrite existing key/values.
def _annotate(self, args, kwargs, select=True):

Undocumented

def _batched_insert(self, objs, fields, batch_size, ignore_conflicts=False):
Helper method for bulk_create() to insert objs one batch at a time.
def _chain(self):
Return a copy of the current QuerySet that's ready for another operation.
def _clone(self):
Return a copy of the current QuerySet. A lightweight alternative to deepcopy().
def _combinator_query(self, combinator, *other_qs, all=False):

Undocumented

def _earliest(self, *fields):
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):
Prepare params for creating a model instance based on the given kwargs; for use by get_or_create().
def _fetch_all(self):

Undocumented

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

Undocumented

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

Undocumented

def _has_filters(self):
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, ignore_conflicts=False):
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):

Undocumented

def _merge_known_related_objects(self, other):
Keep track of all known related objects from either QuerySet instance.
def _merge_sanity_check(self, other):
Check that two QuerySet classes may be merged.
def _next_is_sticky(self):

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):

Undocumented

def _prefetch_related_objects(self):

Undocumented

def _prepare_for_bulk_create(self, objs):

Undocumented

def _raw_delete(self, using):
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):
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):

Undocumented

def complex_filter(self, filter_obj):

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.

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

Undocumented

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

Undocumented

_db =

Undocumented

_defer_next_filter: bool =

Undocumented

_deferred_filter =

Undocumented

_fields =

Undocumented

_for_write: bool =

Undocumented

_hints =

Undocumented

_iterable_class =

Undocumented

_known_related_objects: dict =

Undocumented

_prefetch_done: bool =

Undocumented

_prefetch_related_lookups: tuple =

Undocumented

_query =

Undocumented

_result_cache =

Undocumented

_sticky_filter: bool =

Undocumented

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