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들을 생성한다.
//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)
INSTALLED_APPS = [
'polls.apps.PollsConfig',
...
]
python manage.py makemigrations polls
python manage.py sqlmigrate polls 0001
python manage.py migrate
model과 migrate에서 다음 3가지를 기억하라
1. model.py에서 model을 변경
2. python manage.py makemigrateions를 통해 model의 변경사항을 Django에 알리고 파일로 저장
3. python manage.py migrate를 통해 model의 변경사항을 DB에 반영
** manage.py 유틸리티로 할 수 있는 다양한 기능은 다음 문서를 참조 : https://docs.djangoproject.com/ko/3.0/ref/django-admin/
*** todo : model 시간 설정
대화식 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는 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 객체에 대해 아래의 기능을 지원한다.
또한 각 object들의 변경 history를 볼 수 있다.