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?
Here’s what’s happening, why you’re getting the foreign‐key errors, and two ways to fix it:
Order of insertion
You’re simply iterating over eligible_models in whatever order Django happens to load them. If you hit a child table (Books) before its parent (Author), you’ll try to insert Books whose author_id doesn’t exist yet in the target—hence the “FOREIGN KEY constraint failed.”
PK‐remapping when you don’t preserve pks
When you run with --preserve-pks=False, you do
python
for obj in objs:
setattr(obj, obj._meta.pk.attname, None)
bulk_create(objs)
Django will INSERT new PKs, but the already‐attached FK fields on those in‐memory obj instances still point to the old PKs. So even if the parent row exists, the child FK is pointing at a non-existent key.
Two strategies to fix
A) Topological sort your models & require --preserve-pks
The simplest robust fix is:
Insist on --preserve-pks (so your FKs still point at the correct integers).
Sort your models in dependency order (parents before children).
Here’s a sketch of how to do that in your command:
python
from collections import defaultdict, deque
def topo_sort_models(models):
# Build graph: model -> set(of models it depends on via FK)
deps = defaultdict(set)
reverse = defaultdict(set)
for model in models:
model_label = model._meta.label_lower
for f in model._meta.get_fields():
if f.is_relation and not f.auto_created and f.many_to_one:
parent = f.remote_field.model
parent_label = parent._meta.label_lower
deps[model_label].add(parent_label)
reverse[parent_label].add(model_label)
# Kahn's algorithm
queue = deque(m for m in deps if not deps[m]) # those with no deps
sorted_labels = []
while queue:
lbl = queue.popleft()
sorted_labels.append(lbl)
for child in list(reverse[lbl]):
deps[child].remove(lbl)
if not deps[child]:
queue.append(child)
if len(sorted_labels) != len(models):
raise CommandError("Circular FK dependency detected!")
# Map labels back to model classes
label_to_model = {m._meta.label_lower: m for m in models}
return [label_to_model[l] for l in sorted_labels]
class Command(BaseCommand):
# … your add_arguments …
def handle(self, *args, **options):
preserve_pks = options['preserve_pks']
if not preserve_pks:
raise CommandError("Non-preserve-pks mode is not supported by this command yet.")
# … validate db aliases, migrations, build eligible_models …
# Sort them so parents come first:
eligible_models = topo_sort_models(eligible_models)
for model in tqdm(eligible_models, desc="Migrating models"):
# Now you can safely bulk_create with the original PKs:
objs = list(model.objects.using(from_db).all())
if not objs:
continue
with transaction.atomic(using=to_db):
model.objects.using(to_db).bulk_create(objs, batch_size=500)
self.stdout.write(self.style.SUCCESS(
f"Migrated {len(objs)} rows of {model._meta.label}"
))
self.stdout.write(self.style.SUCCESS("✔ Done."))
That guarantees:
Parents go in first. No “missing parent” FK errors.
You keep the same PK so your child FKs still line up.
B) Remap PKs (advanced)
If you really want --preserve-pks=False, you have to:
For each model, keep a mapping old_pk → new_pk.
After you bulk_create the children, re–assign all FK attributes on the in-memory instances to the new PKs before insertion.
That gets messy, because bulk_create on Postgres/MySQL doesn’t populate the new pks back into your Python objects.
You’d need to either insert one by one (slow) or do a raw RETURNING id batch query and stitch them back.
Unless you have a very good reason to re-number every PK, I’d strongly recommend strategy A: preserve the keys and simply sort by dependency.
— Let me know if that helps or if you’d like a hand with a full “old→new pk” remapping implementation!
Below is a revised version of your command which:
Assumes that all “mainstream” back-ends (SQLite, MySQL, PostgreSQL, Oracle, SQL Server) will happily accept explicit primary‐key inserts, so it always preserves PKs.
Raises an error if you pass --preserve-pks=False on an unknown database engine (since we don’t implement an old→new PK remapping layer).
Topologically sorts your models so that parent tables are inserted before children, avoiding “foreign‐key constraint failed.”
python
import os
from collections import defaultdict, deque
from django.apps import apps
from django.conf import settings
from django.core.management import call_command
from django.core.management.base import BaseCommand, CommandError
from django.db import connections, transaction
from django.db.migrations.executor import MigrationExecutor
from tqdm import tqdm
def topo_sort_models(models):
"""
Kahn’s algorithm: sort models so that any FK target (parent)
is inserted before the FK source (child).
"""
# Build dependency graph: { model_label: set(of parent_labels) }
deps = defaultdict(set)
reverse = defaultdict(set)
label_map = {}
for m in models:
lbl = m._meta.label_lower
label_map[lbl] = m
# scan foreign‐keys (many_to_one)
for f in m._meta.get_fields():
if f.is_relation and not f.auto_created and f.many_to_one:
parent = f.remote_field.model
parent_lbl = parent._meta.label_lower
deps[lbl].add(parent_lbl)
reverse[parent_lbl].add(lbl)
# start with models having no deps
queue = deque(m for m in deps if not deps[m])
sorted_labels = []
while queue:
lbl = queue.popleft()
sorted_labels.append(lbl)
for child in list(reverse[lbl]):
deps[child].remove(lbl)
if not deps[child]:
queue.append(child)
if len(sorted_labels) != len(models):
raise CommandError("Circular FK dependency detected among your models!")
# return classes in sorted order
return [label_map[lbl] for lbl in sorted_labels]
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 DB alias from DATABASES setting.')
parser.add_argument('--to', dest='to_db', required=True,
help='Target DB 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')
# Validate aliases
for alias in (from_db, to_db):
if alias not in settings.DATABASES:
raise CommandError(f"Database alias '{alias}' not found in settings.DATABASES")
# Prepare target DB
self.stdout.write(self.style.WARNING(f"Checking and preparing target database '{to_db}'..."))
self.ensure_target_db_ready(to_db)
# Decide on PK‐preservation strategy
engine = settings.DATABASES[to_db]['ENGINE']
supported = ('sqlite3', 'postgresql', 'mysql', 'oracle', 'sql_server')
if not preserve_pks:
if any(key in engine for key in supported):
self.stdout.write(self.style.WARNING(
"Ignoring `--preserve-pks=False`. "
"All mainstream back-ends support explicit PKs, so we’ll always preserve them."
))
preserve_pks = True
else:
raise CommandError(
f"Engine '{engine}' may not accept explicit PK inserts; "
"pk‐mapping not implemented."
)
self.stdout.write(self.style.SUCCESS(f"Starting data migration: {from_db} → {to_db}"))
# Gather eligible models
all_models = apps.get_models()
eligible = []
for m in all_models:
lbl = f"{m._meta.app_label}.{m.__name__}"
if m._meta.abstract or m._meta.proxy or not m._meta.managed:
continue
if apps_filter and m._meta.app_label not in apps_filter:
continue
if m._meta.app_label in excludes or lbl in excludes:
continue
eligible.append(m)
if not eligible:
self.stdout.write(self.style.WARNING("No models eligible for migration."))
return
# Topo‐sort so parents come before children
eligible = topo_sort_models(eligible)
# Migrate each model in order
for model in tqdm(eligible, desc="Migrating models", unit="model"):
label = f"{model._meta.app_label}.{model.__name__}"
if interactive:
ans = input(f"Migrate model {label}? [y/N]: ").lower()
if ans != 'y':
self.stdout.write(self.style.WARNING(f" Skipping {label}"))
continue
qs = model.objects.using(from_db).all()
count = qs.count()
if count == 0:
continue
if dry_run:
self.stdout.write(f"[DRY RUN] Would migrate {count} objects from {label}")
continue
# load into memory
objs = list(qs)
# always preserving PKs, so NO resetting here
# bulk‐create in one transaction
with transaction.atomic(using=to_db):
model.objects.using(to_db).bulk_create(objs, batch_size=500)
# handle many-to-many (only for non‐auto through tables)
m2m_fields = [
f for f in model._meta.many_to_many
if not f.remote_field.through._meta.auto_created
]
if m2m_fields:
for old in objs:
new = model.objects.using(to_db).get(pk=getattr(old, old._meta.pk.attname))
for f in m2m_fields:
# copy all relations
related = list(getattr(old, f.name).using(from_db).all())
getattr(new, f.name).set(related, bulk=False)
self.stdout.write(self.style.SUCCESS(f"Migrated {len(objs)} objects: {label}"))
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 SQLite, ensure file exists
if 'sqlite3' in engine:
path = db_settings['NAME']
if not os.path.exists(path):
self.stdout.write(f" Creating SQLite file at {path}")
open(path, 'w').close()
# Apply migrations if necessary
conn = connections[to_db]
executor = MigrationExecutor(conn)
plan = executor.migration_plan(executor.loader.graph.leaf_nodes())
if plan:
self.stdout.write(f" Applying pending migrations on '{to_db}'…")
call_command('migrate', database=to_db, interactive=False, verbosity=0)
else:
self.stdout.write(" Migrations already up-to-date on target.")
Key points
We now always preserve primary keys (so your FKs will line up without extra remapping).
If you explicitly pass --preserve-pks=False, we check your DB engine; if it’s one of the usual suspects we simply ignore your request, otherwise we error out.
Models are inserted in a dependency-safe order (parents → children), eliminating “FOREIGN KEY constraint failed.”