한번에 못한 것은 느낌표.
프로젝트 세팅
가상환경 만들기 : python -m venv venv
가상환경 실행 : venv/Sciprts/activate
장고 설치 : pip install django
DRF 설치 : pip install restframework
freeze : pip freeze > requirements.txt
freeze 설치 : pip install -r requirements.txt
장고 프로젝트 시작 drf_week2 : django-admin startproject drf_week2
깃 이그노어 : .gitignore window macos django python visual studio code
깃 인잇 :git init
깃 애드 :git add .
깃 뉴레포 :github new repo
깃 리모트 추가 drf_week2 : git remote add origin ...
깃 커밋 : git commit -m 'init project'
깃 푸시:git push origin 브랜치
인스톨 앱에 DRF 추가 : 'rest_framework'
언어,시간 변경 : ko-kr Asia/Seoul
서버 실행 : python manage.py runserver
 
시리얼라이저란?
앱 만들기 articles : python manage.py startapp articles
인스톨 앱에 앱 추가 : 'articles'
모델 만들기 Article title,content,created_at,updated_at :
#articles.models.py
 
class Article(models.Model):
title = models.CharFeild(max_length=100)
content = models.TextFeild()
created_at = DateTimeField(auto_now_add=True)
updated_at = DateTimeField(auto_now=True)
마이그레이션즈 : python manage.pt makemigrations
마이그레잇 : python manage.py migrate
admin Article 추가 :
#articles.admin.py
 
from articles.models import Article
 
admin.site.register(Article)
슈퍼유저 추가 : python manage.py createsuperuser
article 글 작성 : http://127.0.0.1:8000/admin/
테이블 확인 : db.sqlite3 articles_article
! 관리자 article 타이틀로 출력 :
def __str__(self):
return self.title
article url 연결
drf_week2 urls에 articles/ 추가:
from django.urls import path, include
 
path('artucles/', include('articles.urls')
articles urls에 index/ index함수 별칭 index:
from articles improt views
 
path('index/', views.index, name='index')
articles views수정, Response, api_view: 
from rest_framework.decorators import api_view
from rest_framework.response import Response
 
@api_view(['GET'])
def index(request):
return Response('안녕~')
데이터 보여주기
모든 객체 가져오기: articles = Articles.objects.all()
그 중에 0번 객체 가져오기: article = Articles[0]
데이터 담기 :
alticle_data = {
'title' : article.title,
'content' : article.content,
'created_at' : article.created_at,
'updated_at' : article.updated_at
}
데이터 보내주기 : return Respons(alticle_data)
시리얼라이즈로 데이터 보내주기
시리얼라이즈 만들기
시리얼라이즈.py 만들기: serializers.py
ArticleSerializer 클래스 만들기:
from rest_framework import serializer
from articles.models import Article
 
ArticleSerializer(serializer.ModelSerializer)
Meta 클래스 만들기:
class Meta:
model = Article
fields = '__all__'
 
!feilds라고 오타를 내고 오래동안 봤다.. 오타 조심하자.
viws 수정하기.
시리얼라이즈 할 모델의 객체 가져오기 :
from article.serializers import ArticleSerializer
 
serializer = ArticleSerializer(article)
시리얼라이즈 데이터 보내주기 : return Response(serializer.data)
여러개 시리얼라이즈 데이터 보내주기 :
serializer = ArticleSirializer(articles, many=True)
데이터 여러개 만들기 : admin/articles/article/
시리얼라이저로 게시글 작성
포스트 방식 추가 : [("POST")}
get일때 : if request.method == "GET":
post 일때: if request.method == "POST":
!포스트일 때 데이터 가져오기 : print(request.data[key]
디시리얼라이즈 : serializer = ArticleSirializer(data= request.data)
!디시리얼라이즈 유효성 검사 : if serializer.is_valid():
디시리얼라이즈 저장 : serializer.save()
시리얼라이즈 데이터 보여주기, 201 메세지 띄워주기 : return Response(serializers.data, status=status.HTTTP_201_CREATED
!유효성 검사 실패시 출력하고, 400 메세지 띄워주기 :else: serializer.errors, status=status.HTTP_400_BAD_REQUEST
content db, 유효성 공백도 가능하게 : null = True, blank = True
마이그레이션 :python manage.py makemigrations
마이그레잇 : python manage.py migrate
상세보기,수정,삭제
get방식 일 때: if request.method == 'GET':
url에서 article_id받아오고, article_view로, 별칭 article_view: path('<int:article_id>/', views.article_view, name='article_view'
views에서 함수 만들기: def article_view(request, article_id):
리퀘스트 메소드 세개 추가:@api_view(['GET', 'PUT', 'DELETE'])
아이디가 같은 객체 가져오기 : article = Article.object(id=article_id)
객체 시리얼라이즈 : serializer = ArticleSerializer(article)
데이터 보여주기 : return Response(serializer.data)
404 에러 보여주기 :
from rest_framework.generics import get_object_or_404
 
article = get_object_or_404(Article, id=article_id)
수정
put 방식 일 때: if request.method == 'PUT':
아이디가 같은 객체 가져오기:article = Articles.object(id=article_id)
시리얼라이즈와 디시리얼라이즈 같이 하기 : serializer = ArticleSirializer(article, request.data)
유효성 검사: serializer.is_valid()
저장 : serializer.save()
데이터 보여주기 : return Response(serializer.data)
수정해보기 : http://127.0.0.1:8000/articles/1/
삭제
DELETE 방식일 때: if request.method == 'DELETE':
아이디가 같은 객체 가져오기: article = get_object_or_404(Article, id=article_id)
삭제하기:article.delete()
status 보여주기 204: return Response(status=status.HTTP_204_NO_CONTENT)
url수정해서 홈 화면이 index가 되도록 수정, 함수도 articleAPI로 수정:
상세보기 함수 수정하기 articleDetailAPI로 :
 
 
 
 
 

+ Recent posts