Django model: Database access optimization

  • Do database work in the database rather than in Python.
  • At the most basic level, use filter and exclude to do filtering in the database.
  • Use F expressions to filter based on other fields within the same model.
  • Use annotate to do aggregation in the database.
  • Don’t retrieve things you don’t need.
  • Retrieve everything at once if you know you will need it.
  • Use bulk methods to reduce the number of SQL statements.

Related concepts

Database access optimization

Django model: Database access optimization — Structure map

Clickable & Draggable!

Django model: Database access optimization — Related pages: