본문 바로가기

웹/Django

(Django) 3. Django와 PostreSQL 연동

PostgreSQL

객체 관계형 데이터베이스 관리 시스템이다. BSD 라이센스로 배포되어 전세계 오픈소스 개발자들과 관련 기업들이 개발에 참여하고 있다.

1. PostgreSQL (Linux)

1.1 PostgreSQL 설치

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#Linux
# /projectname
apt-get update
apt-get postgresql
service postgresql start #postgresql 실행
ps -ef|grep postgres #실행 확인
su - postgres #관리자 권한 postgres는 관리자 권한으로 실행해야 함
psql #postgresql 접속
>create database databasename;
>create user username with password 'password' #user 생성
>alter role username set client_encoding to 'utf-8';
>alter role username set timezone to 'Asia/Seoul';
>grant all privileges on database projectname to username
>ALTER DATABASE projectname OWNER TO username;
>exit
cs

1.2 PostgreSQL 설정

/etc/postgresql/9.3/main/pg_hba.conf 수정
1
2
3
4
5
6
vim /etc/postgresql/9.3/main/pg_hba.conf
# "local" is for unix domain socket connections only
#변경 전
local    all        all        peer
#변경 후
local     all        all        md5
cs

1
2
3
4
# 서비스 재시작
service postgresql restart
su - postgres
psql -U username -d databasename;
cs

projectname/config/settings.py 수정

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# settings.py
# 변경 전
DATABASES = {
    'default': {
        'ENGINE''django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}
# 변경 후
DATABASES = {
    'default': {
        'ENGINE''django.db.backends.postgresql',
        'NAME''databasename',
        'USER''username',
        'PASSWORD''password',
        'HOST''localhost'
        'PORT''',
    }
}
cs

1.3 Migrate

1
2
python manage.py makemigrations
python manage.py migrate
cs

2. PostgreSQL (Window)

2.1 PostgreSQL 설치

  1. PostgreSQL 홈페이지에서 다운로드
  2. 설치 후 PgAdmin4 실행
    1. 유저 생성
      • Login/Group Roles > Create > Login/Group Role...
    2. 권한 부여
    3. 데이터베이스 생성
      • Database > Create > Database...
        • Database 이름 입력하고 Owner에 생성한 user 선택
  3. Django 프로젝트에서 psycopg2 모듈 설치

1
2
#/projectname/
pip install psycopg2
cs

2.2 Django settings.py 수정(Window)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#projectname/settings.py
# 변경 전
DATABASES = {
    'default': {
        'ENGINE''django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}
# 변경 후
DATABASES = {
    'default': {
        'ENGINE''django.db.backends.postgresql_psycopg2',
        'NAME''databasename',
        'USER''username',
        'PASSWORD''password',
        'HOST''localhost',
        'PORT''5432'
    }
}
cs

2.3 Migrate

1
2
python manage.py makemigrations
python manage.py migrate
cs


' > Django' 카테고리의 다른 글

(Django) 2. Django 설치 및 설정  (0) 2020.04.21
(Django) 1. Django Framework  (0) 2020.04.21