SQL

SQL django와 연동

봄다온 2025. 2. 6. 16:26

책에선 로컬환경에서 진행.
나는 도커에서 연동.

django, postgresql 이미지 다운

# Dockerfile
FROM python:3.9.13-slim
LABEL maintainer="https://github.com/spring0691"
RUN pip install --no-cache-dir django==2.2.28 psycopg2-binary==2.8.6
EXPOSE 8000

# 이미지 다운로드
docker build . -t django2

# 이미지 다운로드(버전 변경가능)
docker pull postgres:11.22-alpine3.19

docker network 생성후 컨테이너 실행

docker network create studySQL

# django 실행 & 접속
docker run --name django2 --network studySQL -itd -p 8000:8000 django2:latest
docker exec -it django2 bash

# postgresql 실행 & 접속(비밀번호 5432 임시로 사용)
docker run --name postgresql --network studySQL -e POSTGRES_PASSWORD=5432 -d -p 5432:5432 postgres:11.22-alpine3.19
docker exec -it postgresql bash
psql -U postgres

# postgresql db생성
create database post_django;

django 앱 생성 및 환경설정

django-admin startproject django_study
cd django_study
python manage.py startapp survey 

django_study 하위의 settings.py를 수정

                ⋮
                ⋮
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'survey' <ㅡㅡ 이부분 추가
]
                ⋮
                ⋮
TIME_ZONE = 'Asia/Seoul'  <ㅡㅡ 타임존 변경 

django db와 postgresql 연동

django_study 하위의 settings.py의 DATABASES 부분을 수정

                ⋮
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'post_django',
        'USER': 'postgres',
        'PASSWORD': '5432',
        'HOST': 'postgresql',  <-- ip주소가 들어가야하지만 도커의 network에서 통신하기때문에 통신할 컨테이너명이 들어감.
        'PORT': '5432' 
    }
}            
                ⋮

연동확인

# django 컨테이너
python manage.py migrate

# postgresql 컨테이너
psql -U postgres post_django
\d

post_django 데이터베이스안에 테이블들이 생겼다.

survey model 생성

연동은 위 단계에서 완료.
간단한 테스트를 위해 survey/models.py에 다음 class를 추가하자.

class Question(models.Model):
    question_text = models.CharField(max_length=80)
    write_date = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.question_text

class Answer(models.Model):
    question = models.ForeignKey(Question,
                    on_delete=models.CASCADE,
                    related_name = 'answer')
    write_text = models.CharField(max_length=80)
    number = models.IntegerField()

    def __str__(self):
        return self.write_text

이후 마이그레이션한다.

python manage.py makemigrations
pytyon manage.py migrate

CURD 명령

장고 쉘을 사용하여 간단하게 CURD 작업을 해보자

# 쉘 진입
python manage.py shell 

# import
from survey.models import Question, Answer
from django.utils import timezone
# CREATE
# save() 함수가 SQL의 insert(삽입)을 수행

s = Question(question_text="질문1", write_date=timezone.now())
s.save()
s = Question(question_text="질문2", write_date=timezone.now())
s.save()
s = Question(question_text="질문3", write_date=timezone.now())
s.save()
s = Question(question_text="질문4", write_date=timezone.now())
s.save()
s = Question(question_text="질문5", write_date=timezone.now())
s.save()
# READ
# 데이터 조회시에는 쿼리셋(queryset)이라는 객체(object)를 사용

# 모든레코드 조회
Question.objects.all()

# 특정레코드만 조회
Question.objects.filter(question_text="질문4")

# 특정레코드 제외하고 나머지 조회
Question.objects.exclude(question_text="질문4")
# UPDATE
# get()함수를 사용하여 인스턴스에 쿼리셋객체를 저장 후 save()함수로 다시저장

s = Question.objects.get(question_text="질문1")
s.question_text = "질문01"
s.save()
# DELETE
# 삭제를 원하는 쿼리셋객체에 delete()함수를 추가한다

Question.objects.filter(question_text="질문4").delete()
Question.objects.all().delete()

데이터 입출력 확인

# django 컨테이너
# 쉘 진입
python manage.py shell 

# import
from survey.models import Question, Answer
from django.utils import timezone

s1 = Question(question_text="질문1", write_date=timezone.now())
s1.save()
a1 = Answer(answer_text="답변1", number=1, question=s1)
a1.save()

# postgresql 컨테이너

postgresql의 post_django안에 앱명_모델명으로 테이블이 생기고 그 안에 데이터가 저장되어있다.

 

'SQL' 카테고리의 다른 글

SQL 6장 실습문제  (0) 2025.02.05
SQL 테이블 열연결 응용  (0) 2025.02.05
SQL 테이블 열연결(JOIN)  (0) 2025.02.05
SQL 테이블 열연결(FROM, WHERE)  (0) 2025.02.05
SQL 테이블 행연결 응용  (0) 2025.02.05