djangodocs.org

743 sections across all versions Narrow to Django 6.0 (current) →

QuerySet API reference

Reference

This document describes the details of the QuerySet API. It builds on the material presented in the model and database query guides, so you’ll probably want to read and understand those documents before reading this one.

Reference QuerySet API reference

Internally, a QuerySet can be constructed, filtered, sliced, and generally passed around without actually hitting the database. No database activity actually occurs until you do something to evaluate the queryset. You can evaluate a QuerySet in the following ways: Iteration.

QuerySet API

Reference QuerySet API reference

Here’s the formal declaration of a QuerySet: classQuerySet(model=None,query=None,using=None,hints=None)[source] : Usually when you’ll interact with a QuerySet you’ll use it by chaining filters. To make this work, most QuerySet methods return new querysets.

Reference QuerySet API reference QuerySet API

The following QuerySet methods evaluate the QuerySet and return something other than a QuerySet. These methods do not use a cache (see Caching and QuerySets). Rather, they query the database each time they’re called.

Ordered queryset

Reference QuerySet API reference QuerySet APIMethods that do not return QuerySetsupdate()

Chaining order_by() with update() is supported only on MariaDB and MySQL, and is ignored for different databases. This is useful for updating a unique field in the order that is specified without conflicts.

QuerySets are lazy

Topic guide Making queries Retrieving objectsRetrieving specific objects with filters

QuerySet objects are lazy – the act of creating a QuerySet doesn’t involve any database activity. You can stack filters together all day long, and Django won’t actually run the query until the QuerySet is evaluated.

Topic guide Making queries Asynchronous queries

Some methods on managers and querysets - like get() and first() - force execution of the queryset and are blocking. Some, like filter() and exclude(), don’t force execution and so are safe to run from asynchronous code.

from_queryset()

Topic guide Managers Custom managersCreating a manager with QuerySet methods

classmethodfrom_queryset(queryset_class) For advanced usage you might want both a custom Manager and a custom QuerySet.