Represent a lazy database lookup for a set of objects.
Attributes
| Attribute | Type | Description |
|---|
| model | Model class = None | The model class that this QuerySet will perform lookups against. |
| query | django.db.models.sql.query.Query | The low-level query object that encapsulates the SQL construction logic, including any deferred filters. |
| ordered | boolean | Returns True if the QuerySet has an explicit order_by() clause, a default model ordering, or is an EmptyQuerySet. |
| totally_ordered | boolean | Returns True if the QuerySet ordering is deterministic, requiring a unique and non-nullable field in the sort criteria. |
| db | string | The alias of the database that will be used if this query is executed, determined by the router and write status. |
| queryset_only | boolean = True | A 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
| Name | Type | Description |
|---|
| model | [Model](../base/model.md?sid=django_db_models_base_model) = None | The model class that this QuerySet will query. |
| query | sql.Query = None | A specific query object to use; if None, a new sql.Query instance is created for the model. |
| using | str = None | The alias of the database to use for the query. |
| hints | dict = None | Dictionary 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
| Type | Description |
|---|
[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
| Type | Description |
|---|
[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
| Name | Type | Description |
|---|
| chunk_size | int = None | The number of records to fetch and cache at a time from the database |
Returns
| Type | Description |
|---|
iterator | A 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
| Name | Type | Description |
|---|
| chunk_size | int = 2000 | The number of records to fetch in each asynchronous batch |
Returns
| Type | Description |
|---|
async_iterator | An 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
| Name | Type | Description |
|---|
| 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
| Type | Description |
|---|
dict | A 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
| Type | Description |
|---|
int | The 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
| Name | Type | Description |
|---|
| args | [Q](utils/q.md?sid=django_db_models_query_utils_q) | Positional filter expressions |
| kwargs | any | Lookup parameters for filtering the query |
Returns
| Type | Description |
|---|
[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
| Name | Type | Description |
|---|
| kwargs | any | Field values for the new model instance |
Returns
| Type | Description |
|---|
[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
| Name | Type | Description |
|---|
| objs | iterable | A collection of unsaved model instances to insert |
| batch_size | int = None | The number of objects to insert in a single SQL query |
| ignore_conflicts | bool = False | If True, ignores duplicate key errors during insertion |
Returns
| Type | Description |
|---|
list | The 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
| Name | Type | Description |
|---|
| objs | iterable | Model instances with updated local state to persist |
| fields | list | The names of the fields to be updated in the database |
Returns
| Type | Description |
|---|
int | The 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
| Name | Type | Description |
|---|
| defaults | dict = None | Values used for creating the object if it does not exist |
Returns
| Type | Description |
|---|
tuple | A 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
| Name | Type | Description |
|---|
| fields | str | Field names used to determine the chronological order |
Returns
| Type | Description |
|---|
[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
| Type | Description |
|---|
[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
| Name | Type | Description |
|---|
| id_list | iterable = None | A list of primary keys or unique field values to fetch |
| field_name | str = 'pk' | The unique field to use as the dictionary key |
Returns
| Type | Description |
|---|
dict | A mapping of field values to model instances |
delete()
@classmethod
def delete() - > tuple
Delete the records in the current QuerySet.
Returns
| Type | Description |
|---|
tuple | A 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
| Name | Type | Description |
|---|
| kwargs | any | Field names and the new values to assign to them |
Returns
| Type | Description |
|---|
int | The number of rows matched and updated |
exists()
@classmethod
def exists() - > bool
Return True if the QuerySet would have any results, False otherwise.
Returns
| Type | Description |
|---|
bool | True 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
| Name | Type | Description |
|---|
| format | str = None | The output format for the explain plan (e.g., 'JSON', 'TEXT') |
Returns
| Type | Description |
|---|
str | The 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
| Name | Type | Description |
|---|
| fields | str | The specific fields to include in the returned dictionaries |
Returns
| Type | Description |
|---|
[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
| Name | Type | Description |
|---|
| kwargs | any | Lookup parameters to restrict the query results |
Returns
| Type | Description |
|---|
[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
| Name | Type | Description |
|---|
| fields | str | The ForeignKey fields to traverse and include in the query |
Returns
| Type | Description |
|---|
[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
| Name | Type | Description |
|---|
| lookups | str | The related fields or Prefetch objects to load |
Returns
| Type | Description |
|---|
[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
| Name | Type | Description |
|---|
| field_names | str | The fields to sort by; prefix with '-' for descending order |
Returns
| Type | Description |
|---|
[QuerySet](queryset.md?sid=django_db_models_query_queryset) | A QuerySet with the specified sort order applied |