🙂 개발 환경 설정
✔ Python 설치
✔ Python 가상환경 설정
- 가상 환경 생성 명령어
$ py -m venv (project-name)
- 가상 환경 활성화
$ (project-name)\Scripts\activate.bat $ deactivate # 비활성화
- Django 설치하기
$ py -m pip install Django $ django-admin version # 버전 체크
🙂 Django Project 생성하기
✔ 새로운 Django 프로젝트 생성
$ django-admin startproject (mysite)
✔ 생성한 프로젝트를 서버에서 실행
$ python manage.py runserver
🙂 Django App 생성하기
project: NAVER / DAUM 같은 사이트
app: 뉴스 / 블로그 / 메일 등의 기능적인 부분
✔ polls 앱 생성
$ python manage.py startapp polls
✔ polls/views.py
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world.")
✔ mysite/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path("admin/", admin.site.urls),
path("polls/", include('polls.urls'))
]
✔ polls/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('',views.index, name='index')
]
🙂 URL 경로(path) 생성하기
✔ polls/views.py
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world.")
def some_url(request):
return HttpResponse("Some url을 구현해 봤습니다.")
✔ polls/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('',views.index, name='index')
path('some_url',views.some_url)
]
🙂 모델 만들기
서버는 정해진 페이지를 보여주는 것이 아니라 DB에 저장된 데이터를 가져와서 보여줌. -> 모델
모델은 코드에 저장된 값을 DB에서 읽어서 보여줌 -> ORM
✔ mysite/settings.py
...
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'polls.apps.PollsConfig',
]
...
✔ 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)
✔ migration 파일 생성하기
$ python manage.py makemigrations polls
✔ migration으로 실행될 SQL 문장 살펴보기
$ python manage.py sqlmigrate polls 0001
✔ migration 실행하기
$ python manage.py migrate
🙂 장고의 다양한 모델 필드 활용하기
Django 공식 문서 / The model layer 참고
✔ 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')
#is_something = models.BooleanField(default=False)
#average_score = models.FloatField(default=0.0)
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
✔ Django 기본 제공 SQLite 데이터베이스 파일
>>> sqlite3 db.sqlite3
✔ 마이그레이션 롤백
#마이그레이션을 0001버전으로 다시 롤백하기
>>> python manage.py migrate polls 0001
🙂 Django Admin - 관리자 계정 생성하고 접속하기
✔ Django Admin(관리자) 계정 생성하기
$ python manage.py createsuperuser
🙂 Django Admin 모델 등록하기
✔ polls/admin.py
from django.contrib import admin
from .models import *
#Register your models here
admin.site.register(Question)
admin.site.register(Choice)
✔ 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')
def __str__(self):
return f'제목: {self.question_text}, 날짜: {self.pub_date}'
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
🙂 Django Shell 사용하기
✔ 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')
def __str__(self):
return f'제목: {self.question_text}, 날짜: {self.pub_date}'
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
✔ Django Shell 실행
$ python manage.py shell
✔ Django Shell
#models.py 파일에 정의된 모든 모델 가져오기
>>> from polls.models import *
>>> Question
#모든 Question,Choice 오브젝트 가져오기
>>> Question.objects.all()
>>> Choice.objects.all()
#첫번째 Choice 오브젝트 가져오기
>>> choice = Choice.objects.all()[0]
>>> choice.id
>>> choice.choice_text
>>> choice.votes
#첫번째 Choice와 연결된 Question 가져오기
>>> choice.question
>>> choice.question.pub_date
>>> choice.question.id
🙂 Django Shell - 현재 시간 구하기
from datetime import datetime
datetime.now()
from django.utils import timezone
timezone.now()
🙂 Django Shell - 레코드 생성하기
>>> from polls.models import *
#"커피 vs 녹차" 라는 내용의 새로운 Question 오브젝트를 생성하고 'q1'이라는 변수에 저장하기
>>> q1 = Question(question_text = "커피 vs 녹차")
#tiemzone을 활용하여 새로운 오브젝트 'q1'의 생성시각을 설정하기
>>> from django.utils import timezone
>>> q1.pub_date = timezone.now()
#새로운 Question 오브젝트 'q1'을 데이터베이스에 저장하기
>>> q1.save()
>>> q3 = Question(question_text = "abc")
>>> q3.pub_date = timezone.now()
>>> q3.save()
#create() 메서드를 활용하여 q3와 연결된 새로운 Choice 오브젝트를 생성하고, choice_text 필드에 값을 넣어주기
>>> q3.choice_set.create(choice_text = "b")
#새로운 Choice 오브젝트를 생성하고 question 필드에 q3 값을 넣어 연결하기
>>> choice_c = Choice(choice_text='c', question=q3)
#새로운 Choice 오브젝트를 데이터베이스에 저장하기
>>> choice_c.save()
🙂 Django Shell - 레코드 수정 및 삭제하기
>>> from polls.models import *
#Question 오브젝트 중 가장 마지막으로 만들어진 것을 가져오기
>>> q = Question.objects.last()
#해당 오브젝트의 question_text에 새로운 내용을 더해 수정하기
>>> q.question_text = q.question_text + '???'
#Choice 오브젝트 중 가장 마지막으로 만들어진 것을 가져오기
>>> choice = Question.objects.last()
#해당 오브젝트에 연결된 Question을 통해서 choice set을 가져오기
>>> choice.queston.choice_set.all()
#해당 오브젝트를 삭제하기
>>> choice.delete()
🙂 Django Shell - 모델 필터링 (Model Filtering)
>>> from polls.models import *
#get() 메서드를 사용하여 조건에 해당하는 오브젝트를 필터링하기
>>> Question.objects.get(id=1)
>>> q = Question.objects.get(question_text__startswith='휴가를')
>>> Question.objects.get(pub_date__year=2023) #get으로 여러가지 오브젝트를 가져오려고 한다면 에러발생
polls.models.Question.MultipleObjectsReturned: get() returned more than one Question
#filter() 메서드를 사용하여 조건에 해당하는 오브젝트를 필터링하기
>>> Question.objects.filter(pub_date__year=2023)
<QuerySet [<Question: 제목: 휴가를 어디서 보내고 싶으세요?, 날짜: 2023-02-05 18:52:59+00:00>, <Question: 제목: 가장 좋아하는 디저트는?, 날짜: 2023-02-05 18:53:27+00:00>, ...]>
>>> Question.objects.filter(pub_date__year=2023).count()
#쿼리셋의 SQL 쿼리 살펴보기
>>> Question.objects.filter(pub_date__year=2023).query
>>> print(Question.objects.filter(pub_date__year=2023).query)
SELECT "polls_question"."id", "polls_question"."question_text", "polls_question"."pub_date" FROM "polls_question" WHERE "polls_question"."pub_date" BETWEEN 2023-01-01 00:00:00 AND 2023-12-31 23:59:59.999999
>>> Question.objects.filter(question_text__startswith='휴가를').query
>>> print(Question.objects.filter(question_text__startswith='휴가를').query)
SELECT "polls_question"."id", "polls_question"."question_text", "polls_question"."pub_date" FROM "polls_question" WHERE "polls_question"."question_text" LIKE 휴가를% ESCAPE '\'
>>> q = Question.objects.get(pk=1)
>>> q.choice_set.all()
>>> print(q.choice_set.all().query)
SELECT "polls_choice"."id", "polls_choice"."question_id", "polls_choice"."choice_text", "polls_choice"."votes" FROM "polls_choice" WHERE "polls_choice"."question_id" = 1
>>> from polls.models import *
#startswith 연산자를 활용하여 오브젝트를 필터링하기
>>> q = Question.objects.filter(question_text__startswith='휴가를')
>>> q2 = Question.objects.filter(pub_date__year=2023)
#contains 연산자를 활용하여 오브젝트를 필터링하기
>>> Question.objects.filter(question_text__contains='휴가')
>>> Choice.objects.all()
>>> Choice.objects.filter(votes__gt=0)
#해당 쿼리셋에 대한 SQL 쿼리를 생성하기
>>> Choice.objects.filter(votes__gt=0).query
>>> print(Choice.objects.filter(votes__gt=0).query)
SELECT "polls_choice"."id", "polls_choice"."question_id", "polls_choice"."choice_text", "polls_choice"."votes" FROM "polls_choice" WHERE "polls_choice"."votes" > 0
>>> choice=Choice.objects.first()
>>> choice.votes=5
>>> choice.save()
#정규표현식을 활용하여 조건에 해당하는 오브젝트들을 필터링하기
>>> Question.objects.filter(question_text__regex=r'^휴가.*어디')
>>> print(Question.objects.filter(question_text__regex=r'^휴가.*어디').query)
SELECT "polls_question"."id", "polls_question"."question_text", "polls_question"."pub_date", "polls_question"."owner_id" FROM "polls_question" WHERE "polls_question"."question_text" REGEXP ^휴가.*어디
🙂 Django 모델 관계기반 필터링
✔ 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')
def __str__(self):
return f'제목: {self.question_text}, 날짜: {self.pub_date}'
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 f'[{self.question.question_text}] {self.choice_text}'
✔ Django Shell
>>> from polls.models import *
#Question의 question_text 필드 값이 '휴가'로 시작하는 모든 Choice 오브젝트를 필터링하기
>>> Choice.objects.filter(question__question_text__startswith='휴가')
#exclude() 메서드를 사용하여 question_text 필드 값이 '휴가'로 시작하는 모든 Choice 오브젝트를 제외하고 필터링하기
>>> Question.objects.exclude(question_text__startswith='휴가')
🙂 Django Shell - 모델 메소드
✔ polls/models.py
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 was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
def __str__(self):
if self.was_published_recently():
new_badge = 'NEW!!!'
else:
new_badge = ''
return f'{new_badge} 제목: {self.question_text}, 날짜: {self.pub_date}'
'데이터엔지니어링' 카테고리의 다른 글
[3주차] 장고 활용한 API서버 만들기 (3) (0) | 2024.04.10 |
---|---|
[3주차] 장고 활용한 API서버 만들기 (2) (0) | 2024.04.09 |
[2주차] 파이썬으로 웹다루기 (5) (0) | 2024.04.05 |
[2주차] 파이썬으로 웹다루기 (4) (0) | 2024.04.04 |
[2주차] 파이썬으로 웹다루기 (3) (2) | 2024.04.03 |