Computer Science/BackEnd

장고 | 장고 공식 문서 내용 정리 #1-1 Getting started : Django at a glance

토마토. 2022. 9. 2. 14:13

Django documentation contents | Django documentation | Django (djangoproject.com)

 

Django documentation contents | Django documentation | Django

Django The web framework for perfectionists with deadlines. Overview Download Documentation News Community Code Issues About ♥ Donate

docs.djangoproject.com

 

<점프 투 장고>에서 전반적인 내용은 훑었지만, 주로 화면을 꾸미는 내용 중심이라 공식 문서로 공부할 필요성을 느꼈다. 하나하나 차근차근 해보자! 화이팅😄

 

 

장고 한 눈에 보기

빠르게 변화하는 환경에서 개발되어서 일반적인 웹 개발을 쉽게 할 수 있다. 

장고(Django)를 이용해서 데이터베이스 기반 웹앱을 작성하는 방법을 알아보자. 

모델 디자인

장고(Django)는 파이썬 코드로 데이터베이스 형태를 다룰 수 있게 하는 ORM(Object Relational Mapping)을 제공한다. 

이 ORM 데이터 모델을 이용해서 다양한 모델을 만들고 데이터베이스 스키마를 해결할 수 있다. 

모델에는 데이터의 항목들과 하는 일 동작이 포함되어 있다. 모델은 django.db.models.Model을 상속받아 만드는 파이썬 클래스이다. 이때 모델을 통해 데이터베이스에 접근할 수 있는 API를 장고에서 제공한다. 이 장고 API란, 데이터 모델에 대해 자동으로 객체를 CRUD할 수 있는 데이터 베이스 추상화 API를 말한다. (사용법 : 쿼리를 |하게 만들기 장고 문서 | 장고 (djangoproject.com)) 데이터베이스에서 객체를 검색할 때 모델 클래스의 admin을 거쳐 QuerySet을 구성한다.

 

모델의 사례를 보자. 

from django.db import models

class Reporter(models.Model):
    full_name = models.CharField(max_length=70)
    
    def __str__(self):
        return self.full_name
    
class Article(models.Model):
    pub_date = models.DateField()
    headline = models.CharField(max_length=200)
    content = models.TextField()
    reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)
    
    def __str__(self):
        return self.headline

데이터베이스에 Reporter와 Article이라는 내용을 저장해줄 것이라는 걸 알 수 있다. 

각 클래스에는 어떤 항목들이 들어가는지 변수로 정의되어 있다. 

 

모델 설치

위 사례에서 models.py 파일에 모델 Reporter와 Article을 클래스로 정의하였다. 

새롭게 정의한 모델을 데이터베이스 테이블로 반영해주기 위해 makemigrations와 migrate 명령어를 실행해준다. 

manage.py와 같은 경로에 있는 터미널에서

 

$ python manage.py makemigrations
$ python manage.py migrate

를 수행해주면 된다. 

이때 makemigrations는 아직 존재하지 않는 테이블에 대해 migrations을 만들어주는 것을 말한다. 

migrate 명령어는 실제 마이그레이션을 실행하고, 데이터베이스에 테이블을 만들어준다. 

 

Python API

Python API를 테스트해보기 위해서 장고 셸을 켜보자. 

$ python manage.py shell
$ python manage.py shell                          
Python 3.8.10 (default, Jun 22 2022, 20:18:18) 
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information. 
(InteractiveConsole)
>>>

이렇게 장고 쿼리를 날릴 수 있는 인터렉티브 콘솔이 실행되었다. 

여기서 장고 데이터베이스와 상호작용할 수 있다. API라는 말에 쫄지 말 것..^_^

 

# 앞서 만든 model을 import해주기
>>> from survey.models import OperatingSystem, SurveyResult

# OperatingSystem 모델에 딸린 모든 객체를 확인하기
>>> OperatingSystem.objects.all()
<QuerySet [<OperatingSystem: OperatingSystem object (1)>, <OperatingSystem: OperatingSystem object (2)>, <OperatingSystem: OperatingSystem object (3)>, <OperatingSystem: OperatingSystem object (4)>]>

# r이라는 새로운 OperatingSystem 객체를 만들기
>>> r = OperatingSystem(name='linux', description='bad ux', price='1') 
>>> r.save()
>>> r.id
5
>>> r.name
'linux'
>>> r.description
'bad ux'
>>> r.price
'1'

# id = 5인 객체가 새로 생겼음을 확인
>>> OperatingSystem.objects.all()
<QuerySet [<OperatingSystem: OperatingSystem object (1)>, <OperatingSystem: OperatingSystem object (2)>, <OperatingSystem: OperatingSystem object (3)>, <OperatingSystem: OperatingSystem object (4)>, <OperatingSystem: OperatingSystem object (5)>]>

# 다른 필터링 조건을 넣어 객체 가져오기
>>> OperatingSystem.objects.get(id=1)
<OperatingSystem: OperatingSystem object (1)>
>>> OperatingSystem.objects.get(name__startswith='l')
<OperatingSystem: OperatingSystem object (5)>>>> OperatingSystem.objects.get(name__contains='li')
<OperatingSystem: OperatingSystem object (5)>
>>> OperatingSystem.objects.get(id=2)
<OperatingSystem: OperatingSystem object (2)>

이런 식으로 장고 셸에서 장고 API를 이용해 데이터베이스에 새로운 데이터를 생성해주거나 할 수 있다. 

 

동적 관리 인터페이스

장고 모델을 정의하고 난 뒤에는 더 다양한 일들을 할 수 있다. 

 

이를 위해 장고 admin 사이트에 모델을 등록해보자. 

from django.contrib import admin
from . import models

admin.site.register(models.Article)

장고 admin의 의의는 비개발자 구성원도 데이터베이스에 참여할 수 있게 한다는 것이다. 

실제 개발 과정에서는 관리자 페이지를 최대한 빨리 개발하고, 직원들이 데이터를 채울 수 있도록 하는 것이 중요하다. 

 

URL 디자인

장고 URL에는 .php, .asp 같은 수식어를 넣지 않아도 된다. 

덕분에 깔끔한 URL 디자인이 가능해진다. 

from django.urls import path
from . import views

urlpatterns = [
    path('articles/<int:year>/', views.year_archive),
    path('articles/<int:year>/<int:month>/', views.month_archive), 
    path('articles/<int:year>/<int:month>/<int:pk>/', views.article_detail),
]

urls.py에서 정의된 urlpatterns를 살펴보자. 

이 파이썬 코드에서는 URL 경로를 Python 콜백 함수 (views.py)에 매핑해준다. 

 

실제 사용할 때 urls.py가 어떤 역할을 하는지 알아보자. 

- 사용자가 페이지를 요청한다(웹 브라우저에 ~/articles/2022/12 요청)

- Django는 urlpatterns에 정의된 경로를 순서대로 비교한다. 

- 요청된 URL과 일치하는 경로를 발견하면 그대로 중지하고 파이썬 함수 view를 호출한다. 

- 만약 일치하는 경로가 없으면 404를 호출한다. 

 

예) 위 경우에서 사용자가 'articles/2022/05/3923'을 요청했을 때

장고가 호출하는 함수는 news.views.article_detail(request, year=2022, month=5, pk=39323)

 

이때 pk란, primary key로 장고에서 생성한 객체를 식별해주는 id 역할을 한다. 

 

view 작성하기
from django.shortcuts import render
from .models import Article

def year_archive(request, year):
    a_list = Article.objects.filter(pub_date__year=year)
    context = {'year':year, 'article_list':a_list}
    return render(request, 'news/year_archive.html', context)

 

views.py의 함수들에서는 HttpResponse 개체를 반환하거나, Http 404 같은 예외를 발생시킨다. 

나중에 GET API를 개발할 때에 model명.objects.filter(pub_date__year=year)를 참고하자! 

 

템플릿 디자인

좀전에 작성한 views.py 코드에서는 render(request, 'news/year_archive.html') 이라고 html을 반환한다. 

이때 year_archive.html을 템플릿을 로드하는 것이다. 

템플릿은 예를 들면 다음과 같이 생겼다. 

{% extends "base.html" %}
{% block title %} Articles for {{year}}{%endblock%}
{%block content%} 
<h1>articles for {{year}}</h1>

{%for article in article_list %} 
    <p>{{article.headline}}</p>
    <p>By {{article.reporter.full_name}} </p>
    <p> Published {{article.pub_date|date:"F j, Y"}}</p>

{% endfor %} 
{% endblock %}