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
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 Bands and Artists have 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 Bands and Artists have 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 …
Topic guide
Making queries
Querying JSONFieldKey, index, and path transforms
classKT(lookup) : Represents the text value of a key, index, or path transform of JSONField. You can use the double underscore notation in lookup to chain dictionary key and index transforms.
Topic guide
Making queries
Example: You can also delete objects in bulk. Every QuerySet has a delete() method, which deletes all members of that QuerySet.
Topic guide
Making queries
Related objectsOne-to-many relationships
If you would like to specify a different manager for a given query you can use the following syntax: If EntryManager performed default filtering in its get_queryset() method, that filtering would apply to the all() call.
Topic guide
For example: The QuerySet API is extensive. You can annotate and aggregate using many built-in database functions. Beyond those, you can create > custom query expressions. Before using raw SQL, explore the ORM.
Topic guide
Performing raw SQL queries
The raw() manager method can be used to perform raw SQL queries that return model instances: Manager.raw(raw_query,params=(),translations=None) This method takes a raw SQL query, executes it, and returns a django.db.models.query.RawQuerySet instance.
Topic guide
Creating forms from models
Model formsets
As with regular formsets, you can use the max_num and extra parameters to modelformset_factory() to limit the number of extra forms displayed.
Topic guide
Django shortcut functions
get_list_or_404()
However, you can also pass a QuerySet instance: The above example is a bit contrived since it’s equivalent to doing: but it can be useful if you are passed the queryset variable from somewhere else.
Topic guide
Migrations
Migration files
… in RunPython operations. This is done by defining a use_in_migrations attribute on the manager class: If you are using the from_queryset() function to dynamically generate a manager class, you need to inherit from the generated class to make it importable: …
Topic guide
Performance and optimization
General approachesGet things right from the start
For example, you might find that you could calculate the same thing - the number of items in a collection, perhaps - in a QuerySet, in Python, or in a template.
Topic guide
Testing tools
Provided test case classes
classTransactionTestCase[source] TransactionTestCase inherits from SimpleTestCase to add some database-specific features: Resetting the database to a known state at the beginning of each test to ease testing and using the ORM. Database fixtures. Test skipping based on database backend features.
Topic guide
Testing tools
Test cases features
See assertJSONEqual() for further details. TransactionTestCase.assertQuerySetEqual(qs,values,transform=None,ordered=True,msg=None)[source] : Asserts that a queryset qs matches a particular iterable of values values. TransactionTestCase.assertNumQueries(num,func,*args,**kwargs)[source] : Asserts that when func is called with *args and **kwargs that num database queries are executed.
Internals
Django Deprecation Timeline
Passing callable arguments to querysets will no longer be possible. BaseCommand.requires_model_validation will be removed in favor of requires_system_checks. Admin validators will be replaced by admin checks. The ModelAdmin.validator_class and default_validator_class attributes will be removed. ModelAdmin.validate() will be removed.
Reference
The Django admin site
ModelAdmin objects
ModelAdmin.search_help_text : Set search_help_text to specify a descriptive text for the search box which will be displayed below it. ModelAdmin.show_full_result_count : Set show_full_result_count to control whether the full count of objects should be displayed on a filtered admin page (e.g.