Move Data From SQLite to PostgreSQL in Django
People ask: Can I use SQLite in production? If not, why not? Is the cost of using another RDBMS justified by the benefits? Which RDBMS should I use?
Short answer: Using PostgreSQL is the safe way to go, but sometimes you can use SQLite. ~https://djangodeployment.com/
Introduction
Django comes pre-configured to communicate with SQLite, a lightweight relational database that comes with the Python distribution. As a result, Django builds an SQLite database for your project by default.
If your app just has a few users and you don’t want them to make a lot of database requests, SQLite is a great alternative.
On the other hand, if your app is mission-critical and will require lots of users with tons of requests, PostgreSQL is the way to go.
In this piece, I will assume that you have your PostgreSQL database set up and move on with setting it up in Django. If you haven't done that, here are some articles to follow download PostgreSQL, create a database.
NOTE: This guide is suitable for those who want to start using PostgreSQL for their project, as well as those who have an SQLite database and want to convert the data to PostgreSQL.
Procedures
Oh great! You made it here. So shall we begin?
- Dump data from your original SQLite database. (Optional)
NOTE: This part is only for those who have a running SQLite database with data.
Type the following in your terminal, the command will dump all the existing data in your SQLite db into a .json file
python manage.py dumpdata > datadump.json
2. Make changes to your ‘settings.py’ file under the DATABASE section.
You need to make sure you pip install psycopg2 in your working environment, Postgres needs it to function.
# Database# https://docs.djangoproject.com/en/3.0/ref/settings/#databasesDATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'db_test', # this is the name of your database
'HOST': 'localhost', # here you put localhost because you're
# running the postgres server locally
'USER': 'postgres', # you put the username you have
# created, "postgres" is the default
# user.
'PASSWORD': 'user_password', # put your user password here
'PORT': '5432' # this is the port by default.
}
}
3. Make Migrations
Run the following command to set up tables in your newly created PostgreSQL db.
python manage.py migrate --run-syncdb
If you’re just looking to set up Postgres with Django without any prior database data to move, skip to step 5
4. Now load the newly created database with existing data
python manage.py loaddata datadump.json
5. Hooray! You have successfully configured PostgreSQL for Django
Now run your server and test out your application.
python manage.py runserver
You’re good to go✨
Watch this guide on YouTube.