Postgres Crash Course for Django Developers

Posted 8 months, 1 week ago

I'm tired of Googling, prompting, and recalling a few Postgres basics to keep a Django project going.

This is written from the point of view of someone who owns a Mac or Linux and on Postgres version 15. I'm currently using postgres.app. In the examples, I'm using a fictitious name "zephyr" for the project name.

Create a new database:

psql -c "CREATE DATABASE notes"
psql -d zephyr -c "CREATE ROLE notes_user WITH LOGIN PASSWORD 'pa55word'"
psql -d zephyr -c "GRANT CREATE ON SCHEMA PUBLIC to notes_user"
psql -d zephyr -c "GRANT CREATE ON DATABASE notes to notes_user"

If you'll be testing, you may also need to add the permission to create a test database:

psql -d notes -c "ALTER USER notes_user CREATEDB"

Reference your database

Inside your .env folder, use -

DB_URL="postgres://notes_user:pa55word@localhost/notes"

Access the database

psql -U notes_user -d notes

Exporting data from a database

Table to CSV

Get into psql and then try:

\COPY app_model TO '/home/my/export.csv' WITH CSV HEADER;