MYSQL Database Copy Using Python/Django

I need to create a copy of the database in my MySQL Server using Django Application

After a little research, i found mysqldump as the better approach

backup_file_path = f"/tmp/{src_database_name}_backup.sql"

backup_db_command = f"mysqldump -h {SQL_DB_HOST} -P 3306 -u {SQL_DB_USER} -p{SQL_DB_PASSWORD} {src_database_name} > {backup_file_path}"

print(backup_db_command)  # TODO: remove

with os.popen(backup_db_command, "r") as p:
    r =
    print(f"Backup Output: {r}")

restore_command = f"mysql -u root -p{SQL_DB_PASSWORD} {dest_database_name} < {backup_file_path}"

with os.popen(restore_command, "r") as p:
    r =
    print(f"Restore Output: {r}")

My Queries:

  1. Any issues with this approach
  2. Any better approaches to do a copy of DB using Either python or Django ORM

You can try Using django-admin, Django’s command-line utility for dumpdata and loaddata.

Use the following command to dump data

  • django-admin dumpdata [app_label[.ModelName] [app_label[.ModelName] ...]] -o database_backup.sql

Use the following command to load data

  • django-admin loaddata database_backup.sql

docs- dump data load data

Back to Top