I have the following django management command to copy data from one database to another:
python
Assistant
User
The idea of implementing the option for preserve-pk came from the notion that it may be needed for the many2many fields to function properly. The question is, can we assume that most databases will be fine receiving data with a pre-set primary key? If yes, then we can skip the added complexity of an additional mapping layer and always preserve the keys. If no, then we will need the mapping. Please adjust my original file whilst adding your sorting of dependent models, and taking the need for a pk mapping on the database-levle into consideration
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
import os
from django.core.management.base import BaseCommand, CommandError
from django.apps import apps
from django.db import connections, transaction, router
from django.db.migrations.executor import MigrationExecutor
from django.core.management import call_command
from django.conf import settings
from tqdm import tqdm
class Command(BaseCommand):
help = 'Migrate data from one database to another.'
def add_arguments(self, parser):
parser.add_argument(
'--from', dest='from_db', required=True,
help='Source database alias from DATABASES setting.'
)
parser.add_argument(
'--to', dest='to_db', required=True,
help='Target database alias from DATABASES setting.'
)
parser.add_argument(
'--apps', nargs='+',
help='App labels to include (e.g. auth core).'
)
parser.add_argument(
'--exclude', nargs='+',
help='List of app or app.Model names to exclude.'
)
parser.add_argument(
'--dry-run', action='store_true',
help='Simulate without writing data.'
)
parser.add_argument(
'--interactive', action='store_true',
help='Confirm step-by-step.'
)
parser.add_argument(
'--preserve-pks', action='store_true',
help='Preserve primary keys when inserting records.'
)
def handle(self, *args, **options):
from_db = options['from_db']
to_db = options['to_db']
apps_filter = options.get('apps')
excludes = options.get('exclude') or []
dry_run = options.get('dry_run')
interactive = options.get('interactive')
preserve_pks = options.get('preserve_pks')
if from_db not in settings.DATABASES:
raise CommandError(f"Database alias '{from_db}' not found in settings.DATABASES")
if to_db not in settings.DATABASES:
raise CommandError(f"Database alias '{to_db}' not found in settings.DATABASES")
self.stdout.write(self.style.WARNING(f"Checking and preparing target database '{to_db}'..."))
self.ensure_target_db_ready(to_db)
self.stdout.write(self.style.SUCCESS(f"Starting data migration: {from_db} → {to_db}"))
models = apps.get_models()
eligible_models = []
for model in models:
full_label = f"{model._meta.app_label}.{model.__name__}"
if model._meta.abstract or model._meta.proxy or not model._meta.managed:
continue
if apps_filter and model._meta.app_label not in apps_filter:
continue
if model._meta.app_label in excludes or full_label in excludes:
continue
eligible_models.append(model)
if not eligible_models:
self.stdout.write(self.style.WARNING("No models eligible for migration."))
return
for model in tqdm(eligible_models, desc="Migrating models", unit="model"):
label = f"{model._meta.app_label}.{model.__name__}"
if interactive:
confirm = input(f"Migrate model {label}? [y/N]: ").lower()
if confirm != 'y':
self.stdout.write(self.style.WARNING(f"Skipping {label}"))
continue
try:
queryset = model.objects.using(from_db).all()
if not queryset.exists():
continue
if dry_run:
self.stdout.write(f"[DRY RUN] Would migrate {queryset.count()} objects from {label}")
continue
# Load data into memory
objs = list(queryset)
# Optional: Reset PKs if not preserving
if not preserve_pks:
for obj in objs:
setattr(obj, obj._meta.pk.attname, None)
with transaction.atomic(using=to_db):
model.objects.using(to_db).bulk_create(objs, batch_size=500)
# M2M fields
m2m_fields = [f for f in model._meta.many_to_many if not f.remote_field.through._meta.auto_created]
if m2m_fields and preserve_pks and not dry_run:
for old_obj in objs:
new_obj = model.objects.using(to_db).get(pk=old_obj.pk)
for m2m_field in m2m_fields:
related_manager = getattr(old_obj, m2m_field.name)
related_objs = list(related_manager.using(from_db).all())
getattr(new_obj, m2m_field.name).set(related_objs)
self.stdout.write(self.style.SUCCESS(f"Migrated {len(objs)} objects: {label}"))
except Exception as e:
self.stderr.write(self.style.ERROR(f"Error migrating {label}: {e}"))
self.stdout.write(self.style.SUCCESS("✔ Data migration complete."))
def ensure_target_db_ready(self, to_db):
db_settings = settings.DATABASES[to_db]
engine = db_settings['ENGINE']
# Create SQLite DB file if needed
if 'sqlite3' in engine:
db_path = db_settings['NAME']
if not os.path.exists(db_path):
self.stdout.write(f"Creating SQLite DB file at {db_path}")
open(db_path, 'w').close()
# Apply migrations if needed
target_connection = connections[to_db]
executor = MigrationExecutor(target_connection)
plan = executor.migration_plan(executor.loader.graph.leaf_nodes())
if plan:
self.stdout.write(f"Applying missing migrations on '{to_db}'...")
call_command('migrate', database=to_db, interactive=False, verbosity=0)
else:
self.stdout.write("Migrations already applied on target database.")
However, when I try to run this it seems to have problems migrating foreign keys, as it throws Error migrating app.Books: FOREIGN KEY constraint failed Error messages. Can you explain me why and help me fix the error?
Ah, I see the thorny little dragon you’ve run into: foreign key constraints.
Let’s walk carefully through what’s happening in your migration command and why you're seeing those dreaded FOREIGN KEY constraint failed messages.
🔎 What’s Happening
When Django enforces foreign key constraints at the database level:
If you insert a row with an FK pointing to a parent that does not yet exist in the target database, the database rejects it.
In your code, you loop through all models in essentially arbitrary order (apps.get_models()), and for each model you dump its rows and bulk-create them.
⚠️ That means you might be migrating a child table (e.g., Book with author_id) before its required parent table (e.g., Author). At that moment, the target DB says: "Nope, I refuse to let you point to something that doesn’t exist," hence the constraint failure.
you're essentially doing a raw insert. Django skips some helpful safe mechanisms (like cascades or inserting in dependency order). Bulk insert says “shovel it in as-is.” If parent rows aren’t there, 💥.
✅ The Fix
You need two main tweaks:
1. Insert in Dependency Order
Django itself knows model dependencies (it uses this when running migrations!). Conveniently, you can rely on the MigrationExecutor.loader.graph to figure out the creation order, or more simply:
Sort models topologically by foreign key dependencies so that parent models get migrated first.
Here’s a simple adjustment:
python
from django.apps import apps
from django.db.models.deletion import Collector
def sort_models_by_dependencies(models):
"""Return models sorted so that parents come before children."""
from django.db.migrations.state import ModelState
from django.db.migrations.topological_sort import stable_topological_sort
model_key = lambda m: (m._meta.app_label, m._meta.model_name)
model_nodes = {model_key(m): m for m in models}
# Build dependency list
dependencies = []
for model in models:
for field in model._meta.fields:
if field.is_relation and field.remote_field and field.remote_field.model not in (None, 'self'):
if not field.remote_field.parent_link:
dependencies.append((model_key(field.remote_field.model), model_key(model)))
# Sort with topological algorithm
ordered_keys = stable_topological_sort(model_nodes.keys(), dependencies)
return [model_nodes[key] for key in ordered_keys]
Then replace your loop:
python
models = apps.get_models()
eligible_models = [...] # as you already filter
eligible_models = sort_models_by_dependencies(eligible_models)
Now, when Book depends on Author, Author is migrated first.
2. Handle Preserving PKs Consistently
If you want to preserve PKs, great—but make sure the parents get the same PKs in the target DB as in the source. Otherwise, foreign keys will point at the wrong row, or no row at all.
Since you already handle --preserve-pks, just make sure:
If preserve-pks is True, insert parents with their original IDs first (no resetting PKs).
If preserve-pks is False, then you can’t immediately trust relationships, because child objects’ FK fields point to stale IDs. In that case, you’d need to remap the IDs—a much deeper undertaking.
So realistically:
If you don’t preserve PKs, ignore FKs or you’ll break them.
If you do preserve PKs, order inserts properly (parents before children), and then FKs will work fine.
3. Defer Many-to-Many Until After Parents and Children
You already handle this, but keep in mind many-to-many intermediary tables reference both sides. So they must come after both models are inserted.
🪄 Practical Minimal Fix
Ensure eligible_models are sorted so dependencies work.
Don’t attempt non-preserved PK migration of foreign-keyed models unless you also implement a mapping dictionary.
And remind yourself: if you run without --preserve-pks, expect foreign keys to break unless you add a mapping system.
🌱 Gentle Summary
Your FOREIGN KEY constraint failures come from the fact that your script is shoveling in child objects before their parent objects exist. Like trying to introduce a baby without introducing its parents first: awkward at social gatherings, catastrophic in SQL.
The fix is to sort models by dependency order, migrate parents first, and either preserve PKs or implement a remapping strategy for FKs.
✨ Suggested next step: Are you trying to preserve the same primary keys between source and target, or are you okay with new PKs? That’s pivotal in deciding whether you need a mapping layer in addition to topological sorting.
Perfect. You’ve put your finger exactly on the crux of the problem:
If you preserve PKs → Relationships "just work," since children point to the same IDs as their parents. This avoids all mapping complexity.
If you don’t preserve PKs → You’d need a mapping dictionary from old IDs → new IDs for every single related field (FKs and M2Ms). That’s a rabbit hole, and not a fun fluffy bunny one.
Now, to the question:
👉 Can we always preserve PKs in relational databases?
Yes, in almost all common scenarios.
PostgreSQL: Fine with manually assigned PKs as long as you don’t violate uniqueness. You might need to reset the sequence afterward if you want autoincrement to keep working.
MySQL / MariaDB: Same as Postgres. Specify explicit IDs, it’s allowed. May need sequence reset.
SQLite: Works the same. Explicit IDs are accepted.
Oracle / MSSQL: Ditto. Explicit values allowed.
So unless you’re migrating into some very, very exotic RDBMS that enforces no-manual-IDs (vanishingly rare), you’re safe to always preserve PKs. It’s more trouble-free and avoids mapping headaches.
✨ Adjusted File
Below is your original management command updated with:
Dependency order sorting of models before migration.
Sequence reset after migration, so autoincrement keeps working if you later insert new rows normally.
Here’s the cleaned code:
python
import os
from django.core.management.base import BaseCommand, CommandError
from django.apps import apps
from django.db import connections, transaction
from django.db.migrations.executor import MigrationExecutor
from django.core.management import call_command
from django.conf import settings
from django.db import models
from tqdm import tqdm
class Command(BaseCommand):
help = 'Migrate data from one database to another.'
def add_arguments(self, parser):
parser.add_argument(
'--from', dest='from_db', required=True,
help='Source database alias from DATABASES setting.'
)
parser.add_argument(
'--to', dest='to_db', required=True,
help='Target database alias from DATABASES setting.'
)
parser.add_argument(
'--apps', nargs='+',
help='App labels to include (e.g. auth core).'
)
parser.add_argument(
'--exclude', nargs='+',
help='List of app or app.Model names to exclude.'
)
parser.add_argument(
'--dry-run', action='store_true',
help='Simulate without writing data.'
)
parser.add_argument(
'--interactive', action='store_true',
help='Confirm step-by-step.'
)
def handle(self, *args, **options):
from_db = options['from_db']
to_db = options['to_db']
apps_filter = options.get('apps')
excludes = options.get('exclude') or []
dry_run = options.get('dry_run')
interactive = options.get('interactive')
if from_db not in settings.DATABASES:
raise CommandError(f"Database alias '{from_db}' not found in settings.DATABASES")
if to_db not in settings.DATABASES:
raise CommandError(f"Database alias '{to_db}' not found in settings.DATABASES")
self.stdout.write(self.style.WARNING(f"Checking and preparing target database '{to_db}'..."))
self.ensure_target_db_ready(to_db)
self.stdout.write(self.style.SUCCESS(f"Starting data migration: {from_db} → {to_db}"))
# Gather eligible models
models = apps.get_models()
eligible_models = []
for model in models:
full_label = f"{model._meta.app_label}.{model.__name__}"
if model._meta.abstract or model._meta.proxy or not model._meta.managed:
continue
if apps_filter and model._meta.app_label not in apps_filter:
continue
if model._meta.app_label in excludes or full_label in excludes:
continue
eligible_models.append(model)
if not eligible_models:
self.stdout.write(self.style.WARNING("No models eligible for migration."))
return
# Sort models by FK dependencies
eligible_models = self.sort_models_by_dependencies(eligible_models)
# Migrate in sorted order
for model in tqdm(eligible_models, desc="Migrating models", unit="model"):
label = f"{model._meta.app_label}.{model.__name__}"
if interactive:
confirm = input(f"Migrate model {label}? [y/N]: ").lower()
if confirm != 'y':
self.stdout.write(self.style.WARNING(f"Skipping {label}"))
continue
try:
queryset = model.objects.using(from_db).all()
if not queryset.exists():
continue
if dry_run:
self.stdout.write(f"[DRY RUN] Would migrate {queryset.count()} objects from {label}")
continue
objs = list(queryset)
# Preserve PKs always!
with transaction.atomic(using=to_db):
model.objects.using(to_db).bulk_create(objs, batch_size=500)
# Handle many-to-many fields
m2m_fields = [f for f in model._meta.many_to_many
if not f.remote_field.through._meta.auto_created]
if m2m_fields and not dry_run:
for obj in objs:
new_obj = model.objects.using(to_db).get(pk=obj.pk)
for m2m_field in m2m_fields:
related_manager = getattr(obj, m2m_field.name)
related_objs = list(related_manager.using(from_db).all())
getattr(new_obj, m2m_field.name).set(related_objs)
# Reset sequences so autoincrement works properly going forward
self.reset_sequences(model, to_db)
self.stdout.write(self.style.SUCCESS(f"Migrated {len(objs)} objects: {label}"))
except Exception as e:
self.stderr.write(self.style.ERROR(f"Error migrating {label}: {e}"))
self.stdout.write(self.style.SUCCESS("✔ Data migration complete."))
def ensure_target_db_ready(self, to_db):
db_settings = settings.DATABASES[to_db]
engine = db_settings['ENGINE']
if 'sqlite3' in engine:
db_path = db_settings['NAME']
if not os.path.exists(db_path):
self.stdout.write(f"Creating SQLite DB file at {db_path}")
open(db_path, 'w').close()
target_connection = connections[to_db]
executor = MigrationExecutor(target_connection)
plan = executor.migration_plan(executor.loader.graph.leaf_nodes())
if plan:
self.stdout.write(f"Applying missing migrations on '{to_db}'...")
call_command('migrate', database=to_db, interactive=False, verbosity=0)
else:
self.stdout.write("Migrations already applied on target database.")
def reset_sequences(self, model, to_db):
"""Ensure DB sequences are aligned after explicit PK inserts."""
connection = connections[to_db]
if connection.vendor not in ("postgresql", "sqlite", "mysql", "oracle"):
return # skip unknown vendors safely
try:
call_command("sqlsequencereset", model._meta.app_label,
database=to_db, interactive=False)
except Exception:
pass # non-fatal
def sort_models_by_dependencies(self, models):
"""Topological sort so parents (FK targets) come before children."""
from django.db.migrations.topological_sort import stable_topological_sort
model_key = lambda m: (m._meta.app_label, m._meta.model_name)
model_nodes = {model_key(m): m for m in models}
dependencies = []
for model in models:
for field in model._meta.fields:
if field.is_relation and field.remote_field and field.remote_field.model not in (None, 'self'):
if not field.remote_field.parent_link:
dependencies.append((model_key(field.remote_field.model), model_key(model)))
ordered_keys = stable_topological_sort(model_nodes.keys(), dependencies)
return [model_nodes[key] for key in ordered_keys]
🚀 Key Points
We always preserve PKs → avoids fk-mapping complexity.
Models sorted by dependencies → parents before children, no FK errors.
Reset sequences afterward so PK autoincrement won’t break later.
This should now let you migrate relational data smoothly, without PK shenanigans or sad broken FKs.
Would you like me to also tighten the reset_sequences so it directly calls the proper SQL inside the same transaction, rather than using call_command("sqlsequencereset") (which just prints SQL by default)?