GET
articles > urls.py:
urlpatterns = [
path('<int:article_id>/', views.articleDetailAPI, name="article_view"),
]
articles > views.py:
from rest_framework.generics import get_object_or_404
@api_view(['GET', 'PUT', 'DELETE'])
def articleDetailAPI(request, article_id):
if request.method == 'GET':
article = get_object_or_404(Article, id=article_id)
serializer = ArticleSerializer(article)
return Response(serializer.data)
PUT
articles > views.py:
@api_view(['GET', 'PUT', 'DELETE'])
def articleDetailAPI(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) # article을 request.data로 바꿔준다!!
if serializer.is_valid(): # POST 할 때와 똑같
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
DELETE
articles > views.py:
@api_view(['GET', 'PUT', 'DELETE'])
def articleDetailAPI(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) # article을 request.data로 바꿔준다!!
if serializer.is_valid(): # POST 할 때와 똑같
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
elif request.method == 'DELETE':
article = get_object_or_404(Article, id=article_id)
article.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
'Django' 카테고리의 다른 글
파이썬 장고 실무 심화 2주차 4_drf-yasg, 클래스형 view(cbv) (3) | 2023.04.21 |
---|---|
포스트맨(Postman) 사용법 (2) | 2023.04.19 |
파이썬 장고 실무 심화 2주차 2_serializer, GET, POST (3) | 2023.04.19 |
파이썬 장고 실무 심화 2주차 1_api view, response (0) | 2023.04.19 |
DRF 시작하기 (0) | 2023.04.19 |