본문 바로가기
내일배움캠프 AI 웹 프로그래밍

내일배움캠프 37일차 TIL_왕초보 '시리얼라이저'배우기2

by thriveview 2023. 9. 26.

36일차에서 이어서 계속하면된다.

 

우리가 만들어둔 이 article을 조회할 수 있는 API를 만들어보자

 

API를 연결해서 URL만들어서 우리가 작성한 모든 게시글들을 조회할 수 있게 해보자

1. drf_week2 ➔ urls.py 
앱을 만들었으니 앱들을 포함해주도록 하자


include도 되어있는지 확인. 안되어있다면 추가 

path("articles/", include("articles.urls") #urlpatterns에 포함시켜
from django.urls import path, include #include도 되었는지 확인



2. articles 에 urls.py 파일이 없으니 만들어라

 

3. drf_week2 ➔ urls.py 에 있는 코드를 articles ➔ urls.py에 복붙하기

복사한 내용에서 필요없는 부분은 지우고 아래와 같이 수정

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path("articles/", include("articles.urls"))
    ]


5.  articles ➔ views.py 에도 index가 없기 때문에 error가 뜰 것임으로 views.py로 가서 index 만들어주자
drf에서 선호하는 방법으로 진행을 하겠지만 순수 django에서 하는 방법도 같이 알아보자 

방법1.
def index(request):
    return HttpResponse("연결!")   #순수 django에서 선호한 방법


방법2.
#drf에서 선호하는 방법

구글링_drf response ➔ Django Rest Framework ➔ Pulling it all together 
➔ 'from rest_framework.response import Response' 부분 복사 ➔

#render은 사용하지 않으니까 지우자 (render은 templete을 돌릴때 사용하는 것)
#drf로 오면서 templete을 사용하지 않음 
#완성된 코드⬇ 

from rest_framework.response import Response

def index(request):
      return Response("연결되었습니다!")

 

여기까지 완료했다면 runserver 해서 사이트 어떻게 뜨는지 확인하러가자 

내주소/articles/index/

에러가 뜨네?

에러 이유를 구글링해서 찾아보자 

 

구글링 결과, api view를 추가하지 않았다고 나오니 추가해보자 아래에서 api_view 복사 

그리고 최종 수정된 모습 (  articles ➔ views.py )

from rest_framework.response import Response
from rest_framework.decorators import api_view #추가

@api_view(['GET'])  #추가추가
def index(request):
      return Response("연결되었습니다!")

api_view라는 것은 rest_framework에서 이런 api들을 가져다가 편안하게 사용할 수 있게 조작할 수 있게 해주는 기능.

새로고침 완료하면 짜잔! 

수고했어 내자신

 

 

db.sqlite3에 저장되어있는 articles_article들을 index에 접속했을때 다 보여주고 싶다. 그러기 위해서는 어떻게 해야할까?

articles ➔ views.py 에서 추가 코딩 

from articles.models import Article #article이 import안되어있어서 추가 
.
.
articles = Article.objects.all()  

 
이제 article을 response안에 담아서 보내보자. response 안에 글 지우고 article 넣기 

아래 코드로 사이트 돌아가서 리프레시하면?

from rest_framework.response import Response
from rest_framework.decorators import api_view
from articles.models import Article

@api_view(['GET'])
def index(request):
    articles = Article.objects.all()
    return Response(articles)

 

 

에러가 나온다.

에러 이유는 Object of type Article is not JSON serializable
보아하니 Response에 담을 수 있는 것은 스프링, 딕셔너리, 리스트 이런건 넣으면 error없이 돌려보낼수있다

예를들어 아래와 같이 바꿔주면, 

에러없는 화면을 볼 수 있다

 

 

자, 그렇다면 
models.py 에 있는 것을 views.py 에 dic으로 바꿔서 담아보자 
아래와 같이 dic형태로 코드 작성해보자 

from rest_framework.response import Response
from rest_framework.decorators import api_view
from articles.models import Article

@api_view(['GET'])
def index(request):
    article = Article.objects.all()
    article = article[0]
    article_data = {
        "title":article.title,
        "content":article.content,
        "created_at":article.created_at,
        "updated_at":article.updated_at,
    }
    return Response(article_data)

다시 리프레시해서 사이트를 보면 작성한 dic이 그대로 반영된것을 볼 수 있다 


그런데 이러한 과정  (dic을만들어서 해야하는 모든 과정) 이게 너무 귀찮다!  
이 모든 데이터를 dic으로 따로해서 만드는것이 귀찮기 때문에 나오는게 바로 시리얼라이즈 !!! (자동화) 

그게 바로 장고 레스트 프레임 워크다

자, 시리얼라이즈를 하기위해서 articles폴더안에 파일을 새로 만들어두자. (파일명 = serializers.py)

다음시간에는 serializer을 이용해서 모델 만들어보고 왜 이게 편한지 배워보자 ✌