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 to return only the needed fields and skipping model instantiation using values() or values_list().
  • Denormalize models: Selective denormalization improves performance by reducing joins at the cost of data consistency. It can also be used for precomputing values, such as the sum of fields or the active status report into an extra column. Compared to using annotated values in queries, denormalized fields are often simpler and faster.
  • Add an index: If a non-primary key gets searched a lot in your queries, consider setting that field's db_index to True in your model definition.
  • Create, update, and delete multiple rows at once: Multiple objects can be operated upon in a single database query with the bulk_create(), update(), and delete() methods. However, they come with several important caveats such as skipping the save() method on that model. So, read the documentation carefully before using them.

As a last resort, you can always fine-tune the raw SQL statements using proven database performance expertise. However, maintaining the SQL code can be painful over time.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset