경량
Database인SQLlite사용
-> 조금 더 좋은databse사용하겠다 싶으면mysite/setting.py에 가서source몇줄만 고치면 된다.
SQLlite를 확인# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3', # SQLlite가 있다 ! !
INSTALLED_APPS를 확인pip로 따온거나INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
INSTALLED_APPS는 Django와 함께 딸려오는 다음의 앱들을 포함합니다.django.contrib.admin – 관리용 사이트. 곧 사용하게 될 겁니다.django.contrib.auth – 인증 시스템.django.contrib.contenttypes – 컨텐츠 타입을 위한 프레임워크.django.contrib.sessions – 세션 프레임워크.django.contrib.messages – 메세징 프레임워크.django.contrib.staticfiles – 정적 파일을 관리하는 프레임워크.
- 이 파일
setting.py은 현재 Django 인스턴스에서 활성화된 모든Django 어플리케이션들의 이름이 담겨 있고,
앱(app)들은 다수의 프로젝트에서 사용될 수 있고, 다른 프로젝트에서 쉽게 사용될 수 있도록 패키징하여 배포할 수 있습니다
migrate을 해서 지금까지의 앱(app)의 변경 사항을 DB에 반영하자base ❯ python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying auth.0010_alter_group_name_max_length... OK
Applying auth.0011_update_proxy_permissions... OK
Applying auth.0012_alter_user_first_name_max_length... OK
Applying sessions.0001_initial... OK
app들 중 몇몇은 최소한 하나 이상의 데이터베이스 테이블을 사용하는데, 그러기 위해서는 Database에서 테이블을 미리 만들 필요가 있다.설문조사 앱 또한 데이터 저장이 필요함
질문(Question)과 질문에 대한 선택(Choice)
질문(Question)내부에는 2가지 데이터
선택(Choice)내부에도 2가지 데이터
polls/models.py 로 가서 만들어 보자
from django.db import models
`
# Create your models here.
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 테이블은 question 테이블을 참조하고 있고, 한개의 퀘스쳔에 여러가지 초이스를 주기 때문에 "one to many" 이다
choice_text = models.CharField(max_length=200) # 선택지
votes = models.IntegerField(default=0) # 표
Django의 앱들은 《꼈다뺐다》할 수 있습니다. 앱을 다수의 프로젝트에서 사용할 수 있으며, 앱을 배포할 수도 있습니다. 특정 Django 사이트에 앱들이 묶여있지 않아도 되기 때문입니다.
INSTALLED_APPS을 통한 활성화
INSTALLED_APPS에 가서 우리가 만들어준 설문조사 app을 활성화에 추가 해줘야겠죠 ~INSTALLED_APPS = [ 'polls.apps.PollsConfig', # 우리가 만든 설문조사 앱인 요것을 추가해준거야/ polls디렉토리에 apps.py 파일에서 PollsConfig 클래스를 활성화를위해 등록을 하겠다 ~ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ]
'polls.apps.PollsConfig'를 추가해준 후,makemigrations을 통한 테이블 설계도 저장-makemigrations 명령어 입력
python manage.py makemigrations polls
makemigrations을 실행시킴으로서, 작업한 변경사항(이 경우에는 새로운 모델을 만든 것)들을 migration으로 저장시키고 싶다는 것 Django에게 알려줘서 저장시킨다.migration이라는 장소를 만들어 요기다가 만든 Model들을 Databse내 테이블로 생성하기 위한 설계도를 만드는(저장하는) 작업임base ❯ python manage.py makemigrations polls
Migrations for 'polls':
polls/migrations/0001_initial.py
- Create model Question
- Create model Choice
polls/migrations/0001_initial.py에 들어가 확인 시, 데이터베이스 내 테이블을 생성하기 위한 설계도가 만들어 진것을 볼 수 있음from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Question',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('question_text', models.CharField(max_length=200)),
('pub_date', models.DateTimeField(verbose_name='date published')),
],
),
migrations.CreateModel(
name='Choice',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('choice_text', models.CharField(max_length=200)),
('votes', models.IntegerField(default=0)),
('question', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='polls.question')),
],
),
]
migrate 통한 테이블 생성migrate 를 실행시켜 데이터베이스에 모델과 관련된 테이블을 생성하자.base ❯ python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, polls, sessions
Running migrations:
Applying polls.0001_initial... OK
지금 테이블 4개를 생성해땅 !! API를 가지고 놀아보까?
API란 ?
- 개발자가 필요한 데이터를 뽑아 낼 수 있도록 만들어 놓은 함수 또는 서버에게 데이터베이스에게 데이터를 입력할 수 있도록 만들어 놓은 함수 같은 거
shell을 가지고 데이터를 확인 할 수 있다.base ❯ python manage.py shell
Python 3.9.1 (default, Dec 11 2020, 06:28:49)
[Clang 10.0.0 ] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
polls.models)내 Choice와 Question이 있는데 "둘다 사용하겠다" 라고 추가를 하는 작업을 하자from polls.models import Choice, Question
Question내 모든 데이터를 갖고 와보자>>> Question.objects.all() # Question내 모든 데이터를 갖기고 와라라는 명령어
<QuerySet []> # 현재는 Question이 없기 때문에 빈게 나온당
Question내의 데이터를 생성해 보자Question 모델에는 퀘스쳔과 발행일이 있다 알지 ? >>> from django.utils import timezone # 발행일 시간을 입력하기 위해서 timezone이라는 라이브러리 가져왔다.
>>> q = Question(question_text="What's new?", pub_date=timezone.now()) # 여기서 처럼 먼저 퀘스쳔넣어주고, 타임존함수로 발행일
>>> q.save() # Question의 변수인 q를 저장해주고
>>> q.id # 요기 id는 내가 모델을 생성할 떄 명시하지 않아도 Django에서 자동으로 만들어주는 필터중 하나임
1
>>> q.question_text # 질문을 볼 수 있구
"What's new?"
>>> q.pub_date # 발행일도 볼 수 있다.
datetime.datetime(2021, 4, 22, 7, 28, 26, 778488, tzinfo=<UTC>)
>>> q.question_text = "What's up?" # 질문 변경 가능
>>> q.save
<bound method Model.save of <Question: Question object (1)>>
>>> q.question_text # 변경 확인
"What's up?"
>>> q.pub_date # 발행일 또한 변경 확인
datetime.datetime(2021, 4, 22, 7, 28, 26, 778488, tzinfo=<UTC>)
>>> Question.objects.all() # 다 가지고 와라 했을 때,
<QuerySet [<Question: Question object (1)>]> # 한개 있으니까 1 뜨는거 보이죠 ?
Question.objects.all() 몇갠지는 알겠는데 어떤 데이터 인지는 구부니가 잘 안돼 ㅡ ㅡ __str__() 메소드를 사용해서 보고싶은 문구를 볼수 있다 ! !!polls/models.py로 가서 __str__() 메소드 추가해보장from django.db import models
# Create your models here.
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __str__(self): # 이거 추가했지 ^^
return self.question_text
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
import datetime
from django.db import models
from django.utils import timezone
# Create your models here.
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
python manage.py shell
import하고 진행해 줘야한다 ^^ 개귀찮띠>>> from polls.models import Choice, Question # 다시 입력 해 줬고
>>> Question.objects.all() # 다시보니 데이터 다 가꼬와했었고, 원래 1나왔었지 ?
<QuerySet [<Question: What's new?>]> # 지금 보니 무슨 질문인지 나왔다 신기방기 지 ?
>>> Question.objects.filter(id=1) # 퀘스쳔 필터 해서 id 1번인 퀘스쳔 가지고 와라 ㅡ ㅡ 첫번 쨰는 와썹이자너 오케 ?
<QuerySet [<Question: What's new?>]>
>>> Question.objects.filter(question_text__startswith='What') # 퀘스쳔 텍스트 중에 what으로 시작하는거 가지고와라 이거여
<QuerySet [<Question: What's new?>]>