첫번째 장고 앱 장성하기, part2
데이터 베이스 설치
mysite/settings.py
기본적으로 SQLite(Python에서 기본 제공)를 사용하도록 구성되어 있다.
- ENGINE - 'django.db.backends.sqlite3', 'django.db.backends.postgresql', 'django.db.backends.mysql', or 'django.db.backends.oracle'
- NAME - 뭐 맘대로 설정
SQLite 를 데이터베이스로 사용하지 않는 경우, USER, PASSWORD, HOST 같은 추가 설정이 반드시 필요합니다. 더 자세한 내용은 DATABASES 문서를 참조해 주세요.
- database 설치 테스트하기
- https://docs.djangoproject.com/ko/2.0/topics/testing/overview/#the-test-database
- TIME_ZONE 변경하기
- Default: 'America/Chicago'
- timezones
- 변경 후: 'Asia/Seoul'
DB Migration
django와 함께 오는 앱이 admin, auth, contenttypes, sessions, message, staticfiles 데이터 베이스를 자동으로 만들기 위해서는 아래 명렁으로 실행
$ python manage.py migrate
만약 위에서 언급한 app이 모두 필요 없다면 installed_apps에서 제거할 어플리케이션을 주석처리하면 된다.
모델 만들기
- 간단한 설문조사 앱을 만들기 위해 Question, Choice라는 두가지 모델을 만들어볼 예정
- Question
- question
- publication date
- Choice
- choice
- vote
# 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) |
위 처럼 app을 만들고, settings.py의 installed_app에 추가
'polls.apps.PollsConfig',
makemigrations을 실행시킴으로써, 새로운 모델을 생성한다
$ python manage.py makemigrations polls
migration이 어떻게 동작하는지 알기 위해서는 아래와 같이 입력, check를 이용하면 데이터베이스를 건들지 않고도 project에서 문제를 확인 데이터베이스에 모델과 관련된 테이블을 생성하기 위해 migrate
$ python manage.py sqlmigrate polls 0001
$ python manage.py check
$ python manage.py migrate
위 단계를 정리하면 데이터베이스를 만들기 위해서는
- models.py에서 모델을 변경
- python manage.py makemigrations를 통해 변경사항에 대해서 migration을 생성
- python manage.py migrate를 통해 변경사항을 데이터베이스에 적용
API 사용하기
$ python manage.py shell
>>> from polls.models import Question, Choice # Import the model classes we just wrote. | |
# 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)>]> |
위에서 결과를 보면 Object의 형태 그대로 출력이 되기 때문에,
아래와 같이 수정을 해보자
from django.db import models | |
from django.db import models | |
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 |
결과를 찍어보면 제대로 나오는 것을 확인수 있음
from polls.models import Question, Choice | |
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() |
Django Admin 모듈
사이트 컨텐츠를 수정하기 위해서는 관리 사이트가 필요한데,
Django는 모델에 대한 관리용 인터페이스를 모두 자동으로 생성
- 관리자 생성하기
python manage.py createsuperuser
/admin 으로 접속하면 관리 페이지가 보일것이다.
사용자와 컨텐츠가 확인 가능한데, 'django.contrib.auth' 모듈에서 제공되는 인증 프레임워크
관리자 사이트에서 pool app을 변경 가능하도록 만들기
# polls/admin.py | |
from django.contrib import admin | |
from .models import Question | |
admin.site.register(Question) |
코드를 추가하고 새로 고침을 하면 관리자가 수정이 가능하게 된다.
[참고]
- https://docs.djangoproject.com/ko/2.0/intro/tutorial02/
'Programming > Web' 카테고리의 다른 글
[Django] 06.자동화된 테스트 (0) | 2017.12.18 |
---|---|
[Django] 05.간단한 폼처리와 소스코드 줄이기 (0) | 2017.12.18 |
[Django] 04. 어플리케이션 View 만들기 (0) | 2017.12.17 |
[Django] 02.프로젝트 만들기 및 시작하기 (간단한 설문조사 어플리케이션 만들기) (0) | 2017.12.17 |
[Django] 01. 설치 및 환경 설정 (0) | 2017.12.17 |