how to migrate from sqlite to postgresql django
Install the PostgreSQL Database Server:
sudo apt-get update sudo apt-get install postgresql postgresql-contrib
Create a PostgreSQL Database and User:
sudo -u postgres psql CREATE DATABASE yourdbname; CREATE USER yourdbuser WITH PASSWORD 'yourpassword'; ALTER ROLE yourdbuser SET client_encoding TO 'utf8'; ALTER ROLE yourdbuser SET default_transaction_isolation TO 'read committed'; ALTER ROLE yourdbuser SET timezone TO 'UTC'; ALTER USER yourdbuser WITH SUPERUSER; \q
Install the PostgreSQL adapter for Python (psycopg2):
pip install psycopg2
Update Django Settings to use PostgreSQL: In your
settings.py
file, update theDATABASES
configuration:python DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'yourdbname', 'USER': 'yourdbuser', 'PASSWORD': 'yourpassword', 'HOST': 'localhost', 'PORT': '5432', } }
Apply Migrations to the PostgreSQL Database:
python manage.py migrate
Dump Data from SQLite:
python manage.py dumpdata > datadump.json
Load Data into PostgreSQL:
python manage.py loaddata datadump.json
Test Your Application: Ensure that your application works as expected with the new PostgreSQL database.
Update Requirements: If you have a
requirements.txt
file, update it to include thepsycopg2
package.Remove SQLite Configuration (Optional): If you no longer need SQLite, you can remove its configuration from
settings.py
.Commit Changes to Version Control (Optional): If you're using version control, commit the changes to your repository.
That's it! Your Django application should now be migrated from SQLite to PostgreSQL.