Search code examples
mysqldjangooptimizationoverhead

Mysql OPTIMIZE TABLE COMMAND within django


There a few questions out there on what OPTIMIZE TABLE COMMAND does. I know that it helps to clear up the overhead that can hang around in fragmented tables. For me there are sometimes that I need to run it and I wanted to create a view to run these commands from within django.

Is the best way to do this using raw SQL or is there some other django orm to help with it?


Solution

  • Raw SQL is the way to go here.

    from django.db import connections, transaction
    cursor = connections['default'].cursor()
    cursor.execute('OPTIMIZE TABLE;')
    transaction.commit_unless_managed(using='my_db_alias')