IT Log

Django Tutorial 02 본문

Open Source/Django

Django Tutorial 02

newly0513 2020. 7. 19. 20:29
728x90
반응형

1. Database Install

 

기본적으로는 SQLite을 사용하도록 구성되어 있습니다. 만약 데이터베이스를 처음 경험해보거나, Django에서 데이터베이스를 한번 경험해 보고 싶다면, SQLite가 가장 간단한 방법입니다. SQLite는 Python에서 기본으로 제공되기 때문에 별도로 설치할 필요가 없습니다. TIME_ZONE의 기본값은 UTC로 서울시간으로 설정하고 싶다면 'Asia/Seoul'로 설정하면 됩니다.

 

다른 지역인 경우 아래 TZ database name에서 찾을 수 있습니다.

Database TIME_ZONE List : https://en.wikipedia.org/wiki/List_of_tz_database_time_zones

 

mystie/settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

TIME_ZONE = 'Asia/Seoul'


다른 DB를 사용하고 싶다면 아래 예시와 같이 작성하시면 됩니다.

 

DB 작성 예시

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'DB이름',
        'USER': 'USER명',
        'PASSWORD': '비밀번호',
        'HOST': 'DB IP',
        'PORT': 'DB PORT',
    }
}

migrate 명령은 INSTALLED_APPS 설정을보고 mysite/settings.py  파일의 데이터베이스 설정 및 앱과 함께 제공된 데이터베이스 마이그레이션에 따라 필요한 데이터베이스 테이블을 만듭니다.

 

Terminal

  1. cd .. ( 현재 위치가 mysite폴더면 됩니다. )
  2. python manage.py migrate

 


2. Model 만들기

polls/models.py

from django.db import models


class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')


class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)


3. Model 활성화

mysite/settings.py

INSTALLED_APPS = [
    'polls.apps.PollsConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

또는

INSTALLED_APPS = [
    'polls',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]


Terminal

  1. python manage.py makemigrations polls
  2. 출력 내용 확인하기

 

makemigrations 명령은 Model이 변경된 사실과 변경사항을 migration에 저장하고 싶다는 뜻 입니다.

 


migrations 확인

polls → migrations → 0001_initial.py

 

 

또는 

 

Terminal

  1. python manage.py sqlmigrate polls 0001
  2. 출력 내용 확인하기



Terminal

  1. python manage.py migrate
  2. 출력내용 확인하기


4. Python shell

Python shell에서 대화식으로 명령을 사용할 수 있습니다.

 

Terminal

  1. python manage.py shell
  2. 아래 코드 실행
from polls.models import Choice, Question
Question.objects.all()

from django.utils import timezone
q = Question(question_text="What's new?", pub_date=timezone.now())
q.save()
q.id

q.question_text

q.pub_date

q.question_text = "What's up?"
q.save()
Question.objects.all()


polls/models.py

from django.db import models
from django.utils import timezone
import datetime

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def __str__(self):
        return self.question_text

    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)


class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

    def __str__(self):
        return self.choice_text


Terminal

  1. python manage.py shell
  2. 아래코드 실행
from polls.models import Choice, Question
Question.objects.all()
Question.objects.filter(id=1)
Question.objects.filter(question_text__startswith='What')

from django.utils import timezone
current_year = timezone.now().year
Question.objects.get(pub_date__year=current_year)

Question.objects.get(id=2)
Question.objects.get(pk=1)
q = Question.objects.get(pk=1)
q.was_published_recently()

q = Question.objects.get(pk=1)
q.choice_set.all()
q.choice_set.create(choice_text='Not much', votes=0)
q.choice_set.create(choice_text='The sky', votes=0)

c = q.choice_set.create(choice_text='Just hacking again', votes=0)
c.question

q.choice_set.all()
q.choice_set.count()

Choice.objects.filter(question__pub_date__year=current_year)
c = q.choice_set.filter(choice_text__startswith='Just hacking')
c.delete()


5. 관리자 생성하기

Terminal

  1. python manage.py createsuperuser
  2. 사용할 Username 입력
  3. 이메일 주소 입력
  4. 비밀번호 입력 / 재입력


Webpage

  1. http://127.0.0.1:8000/admin
  2. 로그인


polls/admin.py

관리사이트에서 수정이 가능하게 만듭니다.


6. 관리 기능 탐색하기

  1. 등록된 Questions를 클릭
  2. What's up?을 클릭
  3. What's up?을 원하는 Text로 수정한 뒤 우측하단 SAVE 클릭

수정된 텍스트로 저장된 것을 확인할 수 있습니다.

 

728x90
반응형

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

Django Tutorial 05  (0) 2020.07.26
Django Tutorial 04  (0) 2020.07.25
Django Tutorial 03  (0) 2020.07.21
Django Tutorial 01  (0) 2020.07.19
Comments