Postgresql

OneDayDev·2023년 12월 28일
0

Django

목록 보기
10/14

시작하기

brew로 postgresql 설치 후 brew services start postgresql로 서비스 실행

psql -U [username] -d [databasename] 명령어로 db로 접속할 수 있다.
참고로, psql 명령어만 실행 시 운영 체제의 사용자 이름으로 username과 databasename가 디폴트 값으로 반영된다.

연동 과정

0. 기존 데이터 백업

python manage.py dumpdata > datadump.json
python manage.py flush # 기존 데이터 삭제

# 나중에 데이터 베이스 설정 변경 후에 
python manage.py loaddata datadump.json

# 만일 loaddata 하는 경우에 
# ...
# Key (app_label, model)=(admin, logentry) already exists.
# 처럼 에러가 발생한 경우 ContentType에 의한 문제일 수 있다. 
# 이 경우에는 python manage.py shell 에서
from django.contrib.contenttypes.models import ContentType
ContentType.objects.all().delete()
# 로 해결할 수 있다 

ContentType

ContentType is a sort of registry of an app's models, intended as an interface to be able to access information about a model without having to know a whole lot about the model specifics.
The django auth framework uses ContentType to map permissions to models. The django admin app tracks changes to its objects via the model LogEntry which itself uses ContentTypes (that's the model that is causing the error you've posted).

If ContentType is queried for a model that it doesn't know already, a new record with that model is created: that means that the makeup of the ContentType table can differ from environment to environment - it depends on the order in which models are requested in.

Seeing that your dump already contains data for ContentType, and assuming that for any model that uses ContentType, the dump also contains the references to that new ContentType table, you should be fine deleting all entries that are currently in the ContentType table of your local, outdated database:)

1. db 생성

create database {databasename}; 

2. 유저 생성

create user root with password 'password';

3. 환경 설정 - 데이터베이스

alter role root set client_encoding to 'utf-8';
alter role root set timezone to 'Aisa/Seoul';

-- 데이터베이스 권한 부여
grant all privileges on database [databasename] to root;

-- 특정 사용자에게 모든 테이블에 대한 SELECT 권한 부여
GRANT SELECT ON ALL TABLES IN SCHEMA public TO [your_user];

-- 향후 생성되는 모든 테이블에 대해 권한 자동 부여 설정
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO [your_user];

4. Django 세팅

4-1. 라이브러리 설치

pip install psycopg2

4-2. settings.py에서 데이터베이스 설정 변경

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'your_database_name',
        'USER': 'your_database_user',
        'PASSWORD': 'your_database_password',
        'HOST': 'localhost',  # 또는 원격 호스트 주소
        'PORT': '5432',       # PostgreSQL의 기본 포트
    }
}
profile
안녕하세요.

0개의 댓글