기본 세팅

 

https://www.django-rest-framework.org/

 

Home - Django REST framework

 

www.django-rest-framework.org

 

# 가상환경에 설치된 목록 확인
pip list
# 설치
pip install django
pip install djangorestframework
pip install django-dotenv
pip freeze > requirements.txt
django-admin startproject drf_week2 .

 

 

 

 

시리얼라이즈

  • 파이썬 객체나 queryset 객체 등을 JSON, XML 형태로 변환하는 것
  • 반대로 JSON 형태를 DB 인스턴스로 변환하는 것은 디시리얼라이즈라고 한다.

JSON 이란?

    Javascript 객체 문법으로 구조화된 데이터를 표현하기 위한 문자 기반의 표준 포맷

     딕셔너리처럼 Key와 Value 값을 가짐

     *parse란? 데이터 해석. deserialization을 포괄 (ex. 압축해제, 코드 컴파일, 브라우저가 html 해석)

 

 

 

 

 (app-models.py)

from django.db import models

class Articles(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField(blank=True, null=True)
    crated_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    #admin 페이지에서 게시글 제목으로 나오게 하기
    def __str__(self):
    	return str(self.title)

 *urls.py, (app)admin.py, (app)urls.py 등의 설정 생략

 

 

(app - views.py)

from rest_framework.response import Response

def articleAPI(response):
    return Response('연결되었습니다.')

 

 

(app - serializers.py 생성)

# field 타이핑 에러 :
#("Creating a ModelSerializer without either the 'fields' attribute or 
#the 'exclude' attribute has been deprecated since 3.3.0, and is now disallowed. 
#Add an explicit fields = '__all__' to the StockSerializer serializer.",)

from articles.models import Articles
from rest_framework import serializers

class ArticleSerialize(serializers.ModelSerializer):
    class Meta:
        model = Articles
        # field 아님. 오타 주의
        fields = '__all__'

 

 

 

 

 

시리얼라이즈 사용X  vs  사용O

from rest_framework.response import Response
from rest_framework.decorators import api_view
from articles.models import Articles
from articles.serializers import ArticleSerialize

#브라우저블 API
@api_view(['GET', 'POST'])
def articleAPI(request):
    articles = Articles.objects.all()
    article = articles[0]
    article_data = {
        'title' : article.title,
        'content' : article.content,
    }
    return Response(article_data)
    

#위와 아래 같은 코드


@api_view(['GET', 'POST'])
def articleAPI(request):
    articles = Articles.objects.all()
    # 여러개의 article을 가져올 때 many =True
    serialize = ArticleSerialize(articles, many=True)
    return Response(serialize.data)

+) 데코레이터 : https://winterakoon.tistory.com/80

 

 

'Python > Django' 카테고리의 다른 글

[DRF] 03. postman-1, swagger  (0) 2023.04.24
[DRF] 02. @api_view  (0) 2023.04.24
11. Django gitignore, 시크릿 키  (0) 2023.04.24
10. Django 폼  (0) 2023.04.24
[DRF] 00.이론  (0) 2023.04.18

+ Recent posts