728x90
반응형
serializers.py 만들고 viwes.py 에 적용
## articles/serializers.py
from rest_framework import serializers
from .models import Article
class ArticleSerializer(serializers.ModelSerializer):
class Meta:
model = Article
fields = '__all__'
## articles/views.py
...
from articles.serializers import ArticleSerializer
@api_view(["GET", "POST"])
def index(request):
articles = Article.objects.all()
article = articles[0]
serializer = ArticleSerializer(article[0])
return Response(serializer.data)
만약 불러올 데이터가 여러개면 serializer에 many=True 옵션을 추가한다
## articles/views.py
@api_view(["GET", "POST"])
def index(request):
articles = Article.objects.all()
serializer = ArticleSerializer(articles, many=True)
return Response(serializer.data)
POST로 데이터 추가하기
## articles/views.py
@api_view(["GET", "POST"])
def index(request):
if request.method == "GET":
articles = Article.objects.all()
serializer = ArticleSerializer(articles, many=True)
return Response(serializer.data)
elif request.method == "POST":
serializer = ArticleSerializer(data = request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
else:
return Response(serializer.errors)
근데 메세지 head부분에 보면 HTTP 200 OK로 되있다
200 OK가 아닌 다른 상태코드를 넣는것이 맞다
HTTP 상태 코드 추가하기
## articles/views.py
...
from rest_framework import status
@api_view(["GET", "POST"])
def index(request):
if request.method == "GET":
articles = Article.objects.all()
serializer = ArticleSerializer(articles, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
elif request.method == "POST":
serializer = ArticleSerializer(data = request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
게시글 상세 페이지
## articles/urls.py
urlpatterns = [
path('index/', views.index, name='index'),
path('<int:article_id>/', views.article_view, name='article_view'),
]
## articles/view.py
@api_view(["GET", "PUT", "DELETE"])
def article_view(request, article_id):
if request.method == "GET":
article = Article.objects.get(id=article_id)
serializer = ArticleSerializer(article)
return Response(serializer.data)
만약 위 코드로 없는 article_id 를 요청하면
http://127.0.0.1:8000/articles/321/
이렇게 디버그가 뜨게 된다.
이걸 해결하는 방법은 여러개가 있지만 편한 방법은 아래와 같다
## articles/view.py
...
from rest_framework.generics import get_object_or_404
@api_view(["GET", "PUT", "DELETE"])
def article_view(request, article_id):
if request.method == "GET":
article = get_object_or_404(Article, id=article_id)
serializer = ArticleSerializer(article)
return Response(serializer.data)
article_view를 추가해서 상세보기, 수정, 삭제 구현하기
## articles/view.py
@api_view(["GET", "PUT", "DELETE"])
def article_view(request, article_id):
if request.method == "GET":
article = get_object_or_404(Article, id=article_id)
serializer = ArticleSerializer(article)
return Response(serializer.data)
elif request.method == "PUT":
article = get_object_or_404(Article, id=article_id)
serializer = ArticleSerializer(article, data = request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_200_OK)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
elif request.method == "DELETE":
article = get_object_or_404(Article, id=article_id)
article.delete()
return Response("삭제 완료", status=status.HTTP_204_NO_CONTENT)
views.py의 이름을 직관적으로 변경
## articles/urls.py
urlpatterns = [
path('', views.articleAPI, name='index'),
path('<int:article_id>/', views.articleDetailAPI, name='article_view'),
]
## articles/views.py
...
def articleAPI(request):
...
def articleDetailAPI(request, article_id):
...
Uploaded by N2T
728x90
반응형