Bird
Raised Fist0
Djangoframework~10 mins

Database migration in production in Django - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Database migration in production
Write migration files
Test migrations locally
Backup production database
Put app in maintenance mode
Run migration commands
Verify migration success
Bring app back online
This flow shows the safe steps to update a production database schema using Django migrations.
Execution Sample
Django
python manage.py makemigrations
python manage.py migrate --noinput
# Backup DB
# Maintenance mode on
# Run migrate
# Maintenance mode off
This code sequence creates migration files, applies them without prompts, and manages production safety steps.
Execution Table
StepActionCommand/OperationResultNotes
1Create migration filespython manage.py makemigrationsNew migration files createdDetects model changes
2Test migrations locallypython manage.py migrateDatabase updated locallyEnsures no errors
3Backup production DBpg_dump or equivalentBackup file createdSafety step before changes
4Enable maintenance modeCustom command or configApp stops serving requestsPrevents user changes during migration
5Run migrations in productionpython manage.py migrate --noinputDatabase schema updatedNo prompts to avoid hangs
6Verify migration successCheck logs and DB schemaNo errors foundConfirms migration applied
7Disable maintenance modeCustom command or configApp resumes normal operationUsers can access app again
8ExitAll steps completedProduction DB updated safelyProcess finished
💡 All migration steps completed successfully, production database schema updated without downtime.
Variable Tracker
VariableStartAfter Step 1After Step 3After Step 5Final
Migration filesNoneCreatedCreatedCreatedCreated
Local DB schemaOldUpdatedUpdatedUpdatedUpdated
Production DB backupNoneNoneCreatedCreatedCreated
Production DB schemaOldOldOldUpdatedUpdated
App statusOnlineOnlineOnlineMaintenance modeOnline
Key Moments - 3 Insights
Why do we backup the production database before running migrations?
Backing up ensures you can restore data if migration causes errors or data loss, as shown in step 3 of the execution_table.
Why use --noinput when running migrations in production?
The --noinput flag prevents the migration command from waiting for user input, avoiding hangs during automated deployment (step 5).
What is the purpose of maintenance mode during migration?
Maintenance mode stops users from making changes during migration, preventing conflicts or partial updates (step 4 and 7).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the app status after step 5?
AOnline
BMaintenance mode
COffline
DUnknown
💡 Hint
Check the 'App status' variable in variable_tracker after step 5.
At which step is the production database backup created?
AStep 3
BStep 1
CStep 5
DStep 7
💡 Hint
Look at the 'Production DB backup' variable in variable_tracker and the execution_table step descriptions.
If we skip enabling maintenance mode, which step would be missing from the execution_table?
AStep 6
BStep 2
CStep 4
DStep 8
💡 Hint
Maintenance mode is enabled at step 4 according to the execution_table.
Concept Snapshot
Django production migration steps:
1. Create migration files with makemigrations.
2. Test migrations locally.
3. Backup production DB.
4. Enable maintenance mode.
5. Run migrate with --noinput.
6. Verify success and disable maintenance mode.
Always backup and prevent user changes during migration.
Full Transcript
This visual execution shows how to safely update a Django production database schema. First, migration files are created and tested locally. Then, a backup of the production database is made to protect data. The app is put into maintenance mode to stop user activity. Next, migrations run with no input to avoid hangs. After verifying success, maintenance mode is turned off and the app resumes normal operation. Variables like migration files, database schema, and app status change step-by-step to ensure a smooth update.

Practice

(1/5)
1. What is the primary purpose of running python manage.py migrate in a Django production environment?
easy
A. To create new migration files based on model changes
B. To apply database schema changes defined in migration files
C. To start the Django development server
D. To reset the database to its initial state

Solution

  1. Step 1: Understand the migrate command

    The migrate command applies changes to the database schema based on migration files already created.
  2. Step 2: Differentiate from makemigrations

    makemigrations creates migration files, but migrate applies them to the database.
  3. Final Answer:

    To apply database schema changes defined in migration files -> Option B
  4. Quick Check:

    migrate applies changes = A [OK]
Hint: migrate applies changes, makemigrations creates files [OK]
Common Mistakes:
  • Confusing migrate with makemigrations
  • Thinking migrate resets the database
  • Believing migrate starts the server
2. Which of the following is the correct command to create new migration files after changing Django models?
easy
A. python manage.py runserver
B. python manage.py migrate
C. python manage.py makemigrations
D. python manage.py flush

Solution

  1. Step 1: Identify the command for creating migrations

    makemigrations scans model changes and creates migration files.
  2. Step 2: Confirm other commands' purposes

    migrate applies migrations, runserver starts server, flush clears data.
  3. Final Answer:

    python manage.py makemigrations -> Option C
  4. Quick Check:

    makemigrations creates files = A [OK]
Hint: makemigrations creates files, migrate applies them [OK]
Common Mistakes:
  • Using migrate instead of makemigrations to create files
  • Confusing runserver with migration commands
  • Using flush to manage migrations
3. Given the following sequence of commands in production:
python manage.py makemigrations
python manage.py migrate

What will happen if a model field was renamed but the migration was not created before running migrate?
medium
A. No changes will be applied to the database schema
B. An error will occur because migrate requires new migration files
C. The database schema will update correctly with the renamed field
D. The old field will be deleted automatically

Solution

  1. Step 1: Understand migration dependency

    migrate applies changes only if migration files exist. Without new migration files, no schema changes happen.
  2. Step 2: Effect of missing migration files

    If you rename a field but skip makemigrations, the database stays unchanged after migrate.
  3. Final Answer:

    No changes will be applied to the database schema -> Option A
  4. Quick Check:

    migrate needs migration files = C [OK]
Hint: Always run makemigrations before migrate to apply changes [OK]
Common Mistakes:
  • Assuming migrate updates schema without migration files
  • Expecting automatic field deletion
  • Thinking migrate throws error without new migrations
4. You ran python manage.py migrate in production but got an error about conflicting migrations. What is the best way to fix this?
medium
A. Use python manage.py migrate --merge to resolve conflicts
B. Manually edit the database tables to match models
C. Ignore the error and restart the server
D. Delete all migration files and recreate them

Solution

  1. Step 1: Identify cause of migration conflicts

    Conflicts happen when multiple migration branches exist. Django offers a merge option to fix this.
  2. Step 2: Use the merge option

    migrate --merge helps combine conflicting migrations safely without deleting files or manual edits.
  3. Final Answer:

    Use python manage.py migrate --merge to resolve conflicts -> Option A
  4. Quick Check:

    migrate --merge resolves conflicts = D [OK]
Hint: Use migrate --merge to fix conflicts safely [OK]
Common Mistakes:
  • Deleting migration files causing data loss
  • Manually editing tables risking corruption
  • Ignoring errors leads to bigger issues
5. In a production environment, you want to add a new non-nullable field to a large existing table without downtime. Which approach is safest?
hard
A. Add the field as non-nullable directly and run migrate
B. Skip migrations and add the field manually in the database
C. Drop the table and recreate it with the new field
D. Add the field with null=True, migrate, then update data and alter to null=False

Solution

  1. Step 1: Understand downtime risks

    Adding a non-nullable field directly can lock the table and cause downtime in production.
  2. Step 2: Use a two-step migration

    First add the field as nullable (null=True), migrate, then fill data, and finally alter to non-nullable (null=False).
  3. Final Answer:

    Add the field with null=True, migrate, then update data and alter to null=False -> Option D
  4. Quick Check:

    Two-step migration avoids downtime = B [OK]
Hint: Add nullable field first, then make non-nullable after data update [OK]
Common Mistakes:
  • Adding non-nullable field directly causing downtime
  • Dropping tables losing data
  • Skipping migrations causing inconsistencies