Shifting From one Database To Another.
Me🤖
Working with databases may sometimes be tough when your database gets corrupted and you have to ditch it, you may also want to migrate from your existing database to a new database you have and you don’t want to lose data, this 5-minute tutorial should help.
HOW TO DUMP DATA INTO A JSON FILE BEFORE DELETING THE DATABASE AND CREATING A NEW DATABASE TO PLACE THE DUMPED DATA INSIDE.(WORKING WITH PYTHON AND SQLITE3 FOR THIS TUTORIAL)
- New-Item -ItemType Directory -Force -Path backups (on powershell create a backups directory)
- python manage.py dumpdata | Out-File -FilePath backups\data_backup.json(dump database data into a json file)
- Remove-Item db.sqlite3(delete the existing database)
- python manage.py migrate (create migrations which will make a new sqlite3 database, if you have not specified a new database yet)
Check the Encoding of the JSON File
- Open the data_backup.json file in a text editor that shows the encoding (e.g., VSCode, Notepad++).
- Ensure that the file is saved with UTF-8 encoding. If it’s not, you can save it as UTF-8:
- In Notepad++: Open the file → go to Encoding → select UTF-8 → Save the file.
- In VSCode: Open the file → click the encoding (usually displayed at the bottom-right) → select Save with Encoding → choose UTF-8.
- python manage.py shell (open the python shell)
- from django.contrib.contenttypes.models import ContentType (command 1)
- ContentType.objects.all().delete() (command2)
- exit()(command 3 to leave the shell)
- python manage.py loaddata backups/data_backup.json (upload the data that you dumped into JSON into your new databse)
Hope This Helps, END.