Skip to main content

QuerySet

Represent a lazy database lookup for a set of objects.

Attributes

AttributeTypeDescription
modelModel class = NoneThe model class that this QuerySet will perform lookups against.
querydjango.db.models.sql.query.QueryThe low-level query object that encapsulates the SQL construction logic, including any deferred filters.
orderedbooleanReturns True if the QuerySet has an explicit order_by() clause, a default model ordering, or is an EmptyQuerySet.
totally_orderedbooleanReturns True if the QuerySet ordering is deterministic, requiring a unique and non-nullable field in the sort criteria.
dbstringThe alias of the database that will be used if this query is executed, determined by the router and write status.
queryset_onlyboolean = TrueA flag on the as_manager method indicating that the resulting manager should only expose QuerySet methods.

Constructor

Signature

def QuerySet(
model: [Model](../base/model.md?sid=django_db_models_base_model) = None,
query: sql.Query = None,
using: str = None,
hints: dict = None
)

Parameters

NameTypeDescription
model[Model](../base/model.md?sid=django_db_models_base_model) = NoneThe model class that this QuerySet will query.
querysql.Query = NoneA specific query object to use; if None, a new sql.Query instance is created for the model.
usingstr = NoneThe alias of the database to use for the query.
hintsdict = NoneDictionary of hints to be used by the database router.

Methods


query()

@classmethod
def query() - > [Query](../sql/query/query.md?sid=django_db_models_sql_query_query)

Returns the underlying SQL query object, ensuring any deferred filters are applied first.

Returns

TypeDescription
[Query](../sql/query/query.md?sid=django_db_models_sql_query_query)The SQL query object associated with this QuerySet

as_manager()

@classmethod
def as_manager() - > [Manager](../manager/manager.md?sid=django_db_models_manager_manager)

Returns a Manager instance that proxies for this QuerySet's methods.

Returns

TypeDescription
[Manager](../manager/manager.md?sid=django_db_models_manager_manager)A Manager instance configured to use this QuerySet class

iterator()

@classmethod
def iterator(
chunk_size: int = None
) - > iterator

An iterator over the results from applying this QuerySet to the database. chunk_size must be provided for QuerySets that prefetch related objects.

Parameters

NameTypeDescription
chunk_sizeint = NoneThe number of records to fetch and cache at a time from the database

Returns

TypeDescription
iteratorA generator yielding model instances

aiterator()

@classmethod
def aiterator(
chunk_size: int = 2000
) - > async_iterator

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

Parameters

NameTypeDescription
chunk_sizeint = 2000The number of records to fetch in each asynchronous batch

Returns

TypeDescription
async_iteratorAn asynchronous generator yielding model instances

aggregate()

@classmethod
def aggregate(
args: [Aggregate](../aggregates/aggregate.md?sid=django_db_models_aggregates_aggregate),
kwargs: [Aggregate](../aggregates/aggregate.md?sid=django_db_models_aggregates_aggregate)
) - > dict

Return a dictionary containing the calculations (aggregation) over the current queryset.

Parameters

NameTypeDescription
args[Aggregate](../aggregates/aggregate.md?sid=django_db_models_aggregates_aggregate)Positional aggregate expressions
kwargs[Aggregate](../aggregates/aggregate.md?sid=django_db_models_aggregates_aggregate)Named aggregate expressions

Returns

TypeDescription
dictA dictionary of aggregate values keyed by their aliases

count()

@classmethod
def count() - > int

Perform a SELECT COUNT() and return the number of records as an integer.

Returns

TypeDescription
intThe total number of records matching the query

get()

@classmethod
def get(
args: [Q](utils/q.md?sid=django_db_models_query_utils_q),
kwargs: any
) - > [Model](../base/model.md?sid=django_db_models_base_model)

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

Parameters

NameTypeDescription
args[Q](utils/q.md?sid=django_db_models_query_utils_q)Positional filter expressions
kwargsanyLookup parameters for filtering the query

Returns

TypeDescription
[Model](../base/model.md?sid=django_db_models_base_model)The single model instance matching the criteria

create()

@classmethod
def create(
kwargs: any
) - > [Model](../base/model.md?sid=django_db_models_base_model)

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

Parameters

NameTypeDescription
kwargsanyField values for the new model instance

Returns

TypeDescription
[Model](../base/model.md?sid=django_db_models_base_model)The newly created and saved model instance

bulk_create()

@classmethod
def bulk_create(
objs: iterable,
batch_size: int = None,
ignore_conflicts: bool = False
) - > list

Insert each of the instances into the database without calling save() or signals.

Parameters

NameTypeDescription
objsiterableA collection of unsaved model instances to insert
batch_sizeint = NoneThe number of objects to insert in a single SQL query
ignore_conflictsbool = FalseIf True, ignores duplicate key errors during insertion

Returns

TypeDescription
listThe list of created model instances

bulk_update()

@classmethod
def bulk_update(
objs: iterable,
fields: list
) - > int

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

Parameters

NameTypeDescription
objsiterableModel instances with updated local state to persist
fieldslistThe names of the fields to be updated in the database

Returns

TypeDescription
intThe number of rows successfully updated

get_or_create()

@classmethod
def get_or_create(
defaults: dict = None
) - > tuple

Look up an object with the given kwargs, creating one if necessary.

Parameters

NameTypeDescription
defaultsdict = NoneValues used for creating the object if it does not exist

Returns

TypeDescription
tupleA tuple of (object, created), where created is a boolean

earliest()

@classmethod
def earliest(
fields: str
) - > [Model](../base/model.md?sid=django_db_models_base_model)

Returns the earliest object according to fields or the model's Meta.get_latest_by.

Parameters

NameTypeDescription
fieldsstrField names used to determine the chronological order

Returns

TypeDescription
[Model](../base/model.md?sid=django_db_models_base_model)The first model instance based on the specified ordering

first()

@classmethod
def first() - > [Model](../base/model.md?sid=django_db_models_base_model)

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

Returns

TypeDescription
[Model](../base/model.md?sid=django_db_models_base_model)The first result in the QuerySet or None

in_bulk()

@classmethod
def in_bulk(
id_list: iterable = None,
field_name: str = 'pk'
) - > dict

Return a dictionary mapping each of the given IDs to the object with that ID.

Parameters

NameTypeDescription
id_listiterable = NoneA list of primary keys or unique field values to fetch
field_namestr = 'pk'The unique field to use as the dictionary key

Returns

TypeDescription
dictA mapping of field values to model instances

delete()

@classmethod
def delete() - > tuple

Delete the records in the current QuerySet.

Returns

TypeDescription
tupleA tuple containing the total number of deleted objects and a breakdown per model

update()

@classmethod
def update(
kwargs: any
) - > int

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

Parameters

NameTypeDescription
kwargsanyField names and the new values to assign to them

Returns

TypeDescription
intThe number of rows matched and updated

exists()

@classmethod
def exists() - > bool

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

Returns

TypeDescription
boolTrue if the query returns at least one record

explain()

@classmethod
def explain(
format: str = None
) - > str

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

Parameters

NameTypeDescription
formatstr = NoneThe output format for the explain plan (e.g., 'JSON', 'TEXT')

Returns

TypeDescription
strThe execution plan output from the database

values()

@classmethod
def values(
fields: str
) - > [QuerySet](queryset.md?sid=django_db_models_query_queryset)

Returns a QuerySet that returns dictionaries instead of model instances.

Parameters

NameTypeDescription
fieldsstrThe specific fields to include in the returned dictionaries

Returns

TypeDescription
[QuerySet](queryset.md?sid=django_db_models_query_queryset)A QuerySet yielding dictionaries of field values

filter()

@classmethod
def filter(
kwargs: any
) - > [QuerySet](queryset.md?sid=django_db_models_query_queryset)

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

Parameters

NameTypeDescription
kwargsanyLookup parameters to restrict the query results

Returns

TypeDescription
[QuerySet](queryset.md?sid=django_db_models_query_queryset)A new QuerySet containing objects that match the given parameters

@classmethod
def select_related(
fields: str
) - > [QuerySet](queryset.md?sid=django_db_models_query_queryset)

Return a new QuerySet instance that will select related objects via SQL joins.

Parameters

NameTypeDescription
fieldsstrThe ForeignKey fields to traverse and include in the query

Returns

TypeDescription
[QuerySet](queryset.md?sid=django_db_models_query_queryset)A QuerySet that follows foreign key relationships

@classmethod
def prefetch_related(
lookups: str
) - > [QuerySet](queryset.md?sid=django_db_models_query_queryset)

Return a new QuerySet instance that will prefetch the specified related objects in separate queries.

Parameters

NameTypeDescription
lookupsstrThe related fields or Prefetch objects to load

Returns

TypeDescription
[QuerySet](queryset.md?sid=django_db_models_query_queryset)A QuerySet configured to perform bulk lookups for related data

order_by()

@classmethod
def order_by(
field_names: str
) - > [QuerySet](queryset.md?sid=django_db_models_query_queryset)

Return a new QuerySet instance with the ordering changed.

Parameters

NameTypeDescription
field_namesstrThe fields to sort by; prefix with '-' for descending order

Returns

TypeDescription
[QuerySet](queryset.md?sid=django_db_models_query_queryset)A QuerySet with the specified sort order applied