How to copy django objects from one DB to the other

Sometimes you need  two databases connections to synchronize objects from one django database to the other.

Setting

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    },
    'old_db': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'old_db/db_24.11.2022.sqlite3',
    },
}

Command


from django.db import models, IntegrityError, DatabaseError
from django.core.management.base import BaseCommand
from page.models import *
import sys, traceback

class Command(BaseCommand):
def handle(self, *args, **options):

pages_old = StaticPage.objects.using('old_db').filter(url_source__icontains='https://www..be/', added__gt='2022-11-20') # YYYY-MM-DD
for page in pages_old:
  page.save(using='default')

 Django documentation

https://docs.djangoproject.com/en/4.1/topics/db/multi-db/ 


            

 

Comments