Home > OS >  Switch to another database in Django
Switch to another database in Django

Time:10-24

I have a django project that was created on an Oracle database and I want to switch to ANOTHER Oracle database. I have followed this tutorial https://pythonfusion.com/switch-database-django/, but there is a problem that not all models are created initially in Django, some are created using inspectdb on existing tables in other databases . Therefore, when using the migrate --database=new command, I get errors about those tables that already existed before Django was created. Is there a way to migrate only the models and tables necessary for Django to work? (users, auth...)

CodePudding user response:

I think you have to take a look at the managed attribute of each model meta class. If managed is true then django will change the model in the database.

Unmanaged model :

class MyModel(models.Model):
    ...

    class Meta:
        managed = False # This means django will ignore MyModel when migrating

Managed model :

class MyManagedModel(models.Model):
    ...

    class Meta:
        managed = True  # This means django will migrate MyManagedModel

More documentation here : https://docs.djangoproject.com/en/4.1/ref/models/options/

CodePudding user response:

Yes you can definitely customize your migration behavior, the command python manage.py makemigrations creates a couple of files that are used to migrate your models into your DB, any who you can still access these files and choose exactly what to include, exclude and even edit them.

Check the following link: https://dev.to/koladev/writing-custom-migrations-in-django-3eli

CodePudding user response:

If I've understood your question correctly, then you're looking to use Django's built-in migrations. To find out which migrations have been run against your new database, run the command manage.py showmigrations --database=new which will show you a list of all migrations that exist within the context of your application. Once that is done, you can manually run the desired migrations (e.g. auth and contenttypes) by running the command manage.py migrate --database=new app_label migration_name. showmigrations command: https://docs.djangoproject.com/en/4.1/ref/django-admin/#django-admin-showmigrations migrate command: https://docs.djangoproject.com/en/4.1/ref/django-admin/#django-admin-migrate

  • Related