Snippets: Python: Django: PostgreSQL Database Config

24th February 2021 at 5:35pm
Snippets: Python: Django

安装完 PG 后,先新建数据库:

# Switch to postgres user
sudo -iu postgres

# Create a new postgres database superuser, enter the password
createuser -s -P squirrel_admin

# Create a new database owned by user created above
createdb -l en_US.UTF-8 -O squirrel_admin squirrel

将 Python 的 PG 库 psycopg2 加入项目中:

poetry add psycopg2

在 Django 的 settings.py 中这样配置:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'squirrel',
        'USER': 'squirrel_admin',
        'PASSWORD': 'password',
        'HOST': '127.0.0.1',
        'PORT': '5432',
        'OPTIONS': {
            'client_encoding': 'UTF8',
            'isolation_level': psycopg2.extensions.ISOLATION_LEVEL_REPEATABLE_READ,
        }
    }
}

PG 默认的事务隔离级别是读已提交,我认为可重复读更佳,在上面的 isolation_level 中配置。