[Answer]-Django database optimization: Should I filter and count in python or use Django's queryset.count()

1👍

Use the Database as much as you can.

Python, or Java, or any other language doesn’t matter. Always use the SQL (if it is a RDBS ). Every time you execute an SQL multiple things happen:

  • Prepare
  • Execute
  • Fetch

You want every single step to be minimal. If you do all of these on the DB, the Prepare/Execute may take longer (but usually is less than all the queries combined), but Fetch (which sometimes is the biggest) becomes 1 (not n), and usually has also less records that the others combined.

Then, do execution plan to optimize your prepare and execution steps.

Next link is for java developers, but actually it can apply to python world too.

Leave a comment