Database

Sometimes, the Django ORM can generate inefficient SQL code. There are several optimization patterns to improve this, as follows:

  • Reduce database hits with select_related: If you are using a OneToOneField or a Foreign key relationship, in forwarding direction, for a large number of objects, then select_related() can perform a SQL join and reduce the number of database hits.
  • Reduce database hits with prefetch_related: For accessing a ManyToManyField method or, a Foreign key relation, in reverse direction, or a Foreign key relation in a large number of objects, consider using prefetch_related to reduce the number of database hits.
  • Fetch only needed fields with values or values_list: You can save time and memory usage by limiting queries ...

Get Django Design Patterns and Best Practices - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.