Django
- 쉽고 빠르게 웹사이트를 개발할 수 있도록 돕는 구성요소로 이루어진 웹 프레임워크
Django 가상환경 설정
- 서로 다른 유형과 목적의 프로젝트를 한 공간에 넣어 관리하면, 매번 하나의 프로젝트를 실행할 때마다 환경을 체크고 변경해주어야 함
- 심한 경우네는 프로젝트 간의 충돌이 발생할 수도 있음
- 이와 같은 문제 방지를 위해 Python 프로젝트를 가상환경에 만들어 사용
- 명령어 (cmd 사용)
# 가상환경 생성
py -m venv project_name
# 생성한 가상환경 활성화
project_name\scripts\activate.bat
Django 설치
# Django 설치하기
py -m pip install Django
Project 생성
# mysite 라는 프로젝트 생성
django-admin startproject mystie(= 예시 프로젝트 이름)
# 프로젝트를 서버에서 실행하기
python manage.py runserver
App 생성하기
# polls 앱 생성하기
$ python manage.py startapp polls
# polls/view.py
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world.")
# mysite/urls.py
from django.conrtib 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 . imort views
urlpatterns = [
path('', views.index, name'index')
]
URL 경로 설정하기
# polls/views.py
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world.")
def some_url(request):
return HttpResponse("Some ulr을 구현해 봤습니다.")
# polls/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('',views.index, name='index')
path('some_url',views.some_url)
]
관계형 DB (RDB) 모델 만들기
# mysite/settings.py
...
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)
cmd활용
# migration 파일 생성하기
$ python manage.py makemigrations polls
# migration으로 실행될 SQL 문장 살펴보기
$ python manage.py sqlmigrate polls 0001
# migration 실행하기
$ python manage.py migrate
# Django에서 기본으로 제공하는 SQLite 데이터베이스 파일
$ sqlite3 db.sqlite3
# 마이그레이션 롤백
python manage.py migrate polls 0001
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
cmd
# 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
#해당 Question과 연결되어 있는 모든 Choice 가져오기
>>> question.choice_set.all()
Django shell - 레코드 생성하기
cmd
# django shell 실행 후 (python manage.py 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 - 레코드 수정 및 삭제
cmd
# django shell 실행 후 (python manage.py 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 - filter
cmd
# django shell 실행 후 (python manage.py shell)
>>> 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
#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 ^휴가.*어디
#Question의 question_text 필드 값이 '휴가'로 시작하는 모든 Choice 오브젝트를 필터링하기
>>> Choice.objects.filter(question__question_text__startswith='휴가')
#exclude() 메서드를 사용하여 question_text 필드 값이 '휴가'로 시작하는 모든 Choice 오브젝트를 제외하고 필터링하기
>>> Question.objects.exclude(question_text__startswith='휴가')
728x90
'ssung_데이터 엔지니어링 > 3주차_장고 활용한 API 서버 만들기' 카테고리의 다른 글
Django 활용하기(5) (1) | 2023.11.03 |
---|---|
Django 활용하기(4) (1) | 2023.11.02 |
Django 활용하기(3) (0) | 2023.11.01 |
Django 활용하기(2) (0) | 2023.10.31 |