Topic guide
Class-based views
Subclassing generic views
Suppose somebody wants to access our book library over HTTP using the views as an API. The API client would connect every now and then and download book data for the books published since last visit.
Topic guide
Using mixins with class-based views
We’ll consider DetailView, which renders a “detail” view of an object, and ListView, which will render a list of objects, typically from a queryset, and optionally paginate them.
Topic guide
Using mixins with class-based views
Building up Django’s generic class-based views
… as declared in the URLConf, and looks the object up either from the model attribute on the view, or the queryset attribute if that’s provided). SingleObjectMixin also overrides get_context_data(), which is used across all Django’s built in class-based views to …
Topic guide
Using mixins with class-based views
Using Django’s class-based view mixins
One way to do this is to combine ListView with SingleObjectMixin, so that the queryset for the paginated list of books can hang off the publisher found as the single object.
Topic guide
Aggregation
Joins and aggregates
… (note how we use 'book' to specify the Publisher -> Book reverse foreign key hop): (Every Publisher in the resulting QuerySet will have an extra attribute called book__count.) We can also ask for the oldest book of any of those …
Topic guide
… can customize the behavior of this fetching with a fetch mode, making it more efficient or even blocking it. Use QuerySet.fetch_mode() to set the fetch mode for model instances fetched by a QuerySet: Fetch modes apply to: ForeignKey fields OneToOneField …
dev
Topic guide
Fetch modes
We’ll explain them below using these models: …and this loop: …where books is a QuerySet of Book instances using some fetch mode. FETCH_ONE Fetches the missing field for the current instance only. This is the default mode.
dev
Topic guide
Managers
Custom managers
… Manager methods.) For example, this custom Manager adds a method with_counts(): With this example, you’d use OpinionPoll.objects.with_counts() to get a QuerySet of OpinionPoll objects with the extra num_responses attribute attached. A custom Manager method can return anything you want. It …
Topic guide
Managers
Custom managers
As a result, it’s a good idea to be careful in your choice of default manager in order to avoid a situation where overriding get_queryset() results in an inability to retrieve objects you’d like to work with.
Topic guide
Managers
Custom managersBase managers
For example, if the Question model from the tutorial had a deleted field and a base manager that filters out instances with deleted=True, a queryset like Choice.objects.filter(question__name__startswith='What') would include choices related to deleted questions.
Topic guide
Managers
Custom managersBase managers
Therefore, you should not override get_queryset() to filter out any rows. If you do so, Django will return incomplete results.
Topic guide
Models
NOTE: The Models Reference Covers all the model related APIs including model fields, related > objects, and QuerySet.
Topic guide
Multiple databases
Manually selecting a database
For example, say you have a custom manager method that touches the database – User.objects.create_user(). Because create_user() is a manager method, not a QuerySet method, you can’t do User.objects.using('new_users').create_user().
Topic guide
Multiple databases
Django’s admin doesn’t have any explicit support for multiple databases.
Topic guide
Database access optimization
…including: Indexes. This is a number one priority, after you have determined from profiling what indexes should be added. Use Meta.indexes or Field.db_index to add these from Django.
Topic guide
Database access optimization
Retrieve related objects efficiently
Use the FETCH_PEERS fetch mode to make on-demand field access more efficient with bulk-fetching. Enable it for all usage of your models with a custom manager.
dev
Topic guide
Database access optimization
Don’t retrieve things you don’t need
If a model has a default ordering (Meta.ordering) and you don’t need it, remove it on a QuerySet by calling order_by() with no parameters. Adding an index to your database may help to improve ordering performance.
Topic guide
Database access optimization
Use bulk methods
When inserting objects into ManyToManyFields, use add() with multiple objects to reduce the number of SQL queries. For example: …is preferable to: …where Band and Artist are models with a many-to-many relationship.
Topic guide
Database access optimization
Use bulk methods
When removing objects from ManyToManyFields, use remove() with multiple objects to reduce the number of SQL queries. For example: …is preferable to: …where Band and Artist are models with a many-to-many relationship.
Topic guide
Making queries
Asynchronous queries
… you can swap to async for: Be aware that you also can’t do other things that might iterate over the queryset, such as wrapping list() around it to force its evaluation (you can use async for in a comprehension, if …