Django tutorial, part 2

김수민·2020년 5월 4일
0

Django+uWSGI+nginx

목록 보기
3/9

https://docs.djangoproject.com/en/3.0/intro/tutorial02/

  • DB setup
  • Django model
  • Django의 자동생성 admin site 소개

DB setup

  • mysite/settings.py 에 다양한 Django 설정 변수들이 있다. 기본적으로 SQLite를 사용하도록 설정되어 있다. 다른 DB를 사용하고 싶다면 추가적인 설정들이 필요하다.

  • INSTALLED_APPS 설정 - 현재 Django 인스턴스에서 활성화 된 Django App들의 이름을 적어둔것. App들은 다수의 project에서 사용될 수 있고, 패키지화 하고 배포할 수 있다.

  • INSTALLED_APPS에는 default App들이 있다.

django.contrib.admin – The admin site. You’ll use it shortly.
django.contrib.auth – An authentication system.
django.contrib.contenttypes – A framework for content types.
django.contrib.sessions – A session framework.
django.contrib.messages – A messaging framework.
django.contrib.staticfiles – A framework for managing static files.

  • 이러한 default App들중에는 DB를 사용하는 것도 있다. 따라서, 아래 명령어를 통해 DB와 table을 설정해주어야 한다.
    python manage.py migrate

  • migrate 명령어는 INSTALLED_APPS 항목을 보고 필요한 DB table들을 생성한다.

Creating models

  • model이란, 하나의 정의된 (single definitive) 실질적인 데이터 소스이다.
  • poll app에서는 두개의 model을 생성할 것이다. Question, Choice
  • Question은 생성일과 질문을 가진다.
  • Choice는 선택에 대한 문자와 투표 수를 가진다.
  • 하나의 Choice는 하나의 Question과 연관된다.
  • 위의 concept은 Python class로 표현되어진다.
//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)
  • 모델 클래스는 models.Model 클래스를 상속받는다.
  • 테이블의 field는 데이터 형식에 따라서 맴버 변수로 선언한다. 관계 설정도 가능하다.

model activating

  • 위에서 생성한 모델 정보를 가지고 Django는 다음과 같은 일은 할 수 있다.
    - DB Schema 생성 (Create Table)
    • Question과 Choice 객체에 접근하기 위한 Python DB API
  • 현재 project에 polls app이 설치되어 있음을 알려야한다.
INSTALLED_APPS = [
    'polls.apps.PollsConfig',
    ...
]
python manage.py makemigrations polls
  • makemigration 명령어를 통해 model을 수정했다는 변경했고, 해당 내용을 migrateion으로 저장하고 싶음을 Django에 알립니다.
  • polls/migrations/ 하위에 migration 파일이 생성된다. 그리고 아래 명령어를 통해 실제 실행되는 SQL문을 볼 수 있다.
python manage.py sqlmigrate polls 0001
  • 이제 실제로 migrate를 실행시켜 DB에 model관련 테이블을 생성한다.
python manage.py migrate
  • migrate 기능은 매우 강력하다. 실제 DB를 건들지 않고 model 작업을 진행 할 수 있다.

model과 migrate에서 다음 3가지를 기억하라
1. model.py에서 model을 변경
2. python manage.py makemigrateions를 통해 model의 변경사항을 Django에 알리고 파일로 저장
3. python manage.py migrate를 통해 model의 변경사항을 DB에 반영

  • makemigrateions와 migrate 명령을 분리한 것은 버전관리와 유지보수를 쉽게하기 위함이다.

** manage.py 유틸리티로 할 수 있는 다양한 기능은 다음 문서를 참조 : https://docs.djangoproject.com/ko/3.0/ref/django-admin/

*** todo : model 시간 설정

API 실습

대화식 Python Shell을 사용하여 Django API를 실습해본다.
다음 명령어로 Python Shell을 실행한다.
python manage.py shell
위와 같이 python shell을 실행하는 이유는, manage.py에 설정된 DJANGO_SETTINGS_MODEL 환경변수를 사용하기 위함이다.

shell에서 아래의 DB API를 실행해본다.


# No questions are in the system yet.
>>> Question.objects.all()
<QuerySet []>

# Create a new Question.
# Support for time zones is enabled in the default settings file, so
# Django expects a datetime with tzinfo for pub_date. Use timezone.now()
# instead of datetime.datetime.now() and it will do the right thing.
>>> from django.utils import timezone
>>> q = Question(question_text="What's new?", pub_date=timezone.now())

# Save the object into the database. You have to call save() explicitly.
>>> q.save()

# Now it has an ID.
>>> q.id
1

# Access model field values via Python attributes.
>>> q.question_text
"What's new?"
>>> q.pub_date
datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<UTC>)

# Change values by changing the attributes, then calling save().
>>> q.question_text = "What's up?"
>>> q.save()

# objects.all() displays all the questions in the database.
>>> Question.objects.all()
<QuerySet [<Question: Question object (1)>]>

<QuerySet [<Question: Question object (1)>]> => 이러한 객체 표현은 보기에 좋지 않으니, polls/models.py에 Question 모델에 str() 메소드를 추가하여 보기 좋게 한다.

** 공홈 document에 있는 다양한 api 예제를 실습해보자.

Django admin site 소개

  • Django는 Lawrence Journal-World 신문사의 프로그래머가 처음 개발했다. 때문에 '게시자'와 '공개'사이트의 구분이 명확하다. '게시자'는 기사들을 사이트에 추가하고, 추가된 컨텐츠를 '공개'사이트에 노출한다.

  • 관리자 생성
    python manage.py createsuperuser

  • 서버 시작
    - /admin/ 으로 admin site에 접속 할 수 있다.

  • 관리사이트에 poll app 추가하기

    from django.contrib import admin
    from .models import Question
    admin.site.register(Question)

  • Qusetion Model로 부터 자동으로 생성된 admin site를 볼 수 있다.

  • Model 객체에 대해 아래의 기능을 지원한다.

    • Save
    • Save and continue editing
    • Save and add another
    • Delete
  • 또한 각 object들의 변경 history를 볼 수 있다.

 
profile
python developer

0개의 댓글