Restore Models from Backup in Django

July 22, 2024, 10:02 p.m.

Restoring data from backups is crucial for maintaining data integrity and recovering from data loss. This guide will show you how to create a Django management command to load specific models from backup JSON files.

This tutorial assumes you already have created a backup in the `backup/` path.

Follow this tutorial Create Backups for All Models

When restoring data from backups, ensure that you upload models with dependencies first. For instance in this case, models like auth.User should be restored before related models such as company.Company and employee.Designation to maintain referential integrity and avoid errors due to missing foreign key relationships.

Step-by-Step Implementation

Create the Management Command

First, create a new management command in your Django application. This involves creating a directory structure as follows:

your_app/
    management/
        __init__.py
        commands/
            __init__.py
            load_from_backup.py

Write the Load Command

In load_from_backup.py, add the following code:

import os
from django.core.management.base import BaseCommand, call_command

class Command(BaseCommand):
    help = "Load models from backup files."

    def handle(self, *args, **options):
        backup_dir = "backup/"

       # Replace with your model name
# Here company is the app name and Company is model name
# employee is app name and Designation is model name
        models_to_load = [
          "auth.User",
            "company.Company",
            "employee.Designation",
            "employee.CustomPermission",
            "employee.Role"
        ]

        for model in models_to_load:
            app_label, model_name = model.split('.')
            filename = os.path.join(backup_dir, f"{app_label.lower()}_{model_name.lower()}.json")

            if os.path.exists(filename):
                self.stdout.write(f"Loading backup for {model}")
                call_command(
                    "loaddata",
                    filename,
                )
                self.stdout.write(self.style.SUCCESS(f"Successfully loaded {model} from {filename}."))
            else:
                self.stdout.write(self.style.ERROR(f"Backup file {filename} does not exist."))

      self.stdout.write(self.style.SUCCESS("All specified models have been loaded from backup."))


How It Works
  • Directory Setup: The script assumes the backup/ directory contains the JSON files for the models.
  • Specify Models: The models_to_load list contains the models you want to load from the backup.
  • Iterate Through Models: The script iterates through the list of models and constructs the filename for each model.
  • Load Data: It uses Django's loaddata command to load the data from the JSON file into the database.
To upload the backup command, run:
python manage.py load_from_backup

This will load the data from the specified JSON files in the backup/ directory into your Django application's database.

Back