Web 개발 :: 파이썬 Django Rest Framework(1) _ 프로젝트 세팅, 모델 Serializer, CRUD 기능 구현
참고 링크
class Article(models.Model):
content = models.TextField(null=True, blank=True)
created_at = models.DateTimeField(auto_now_add = True)
updated_at = models.DateTimeField(auto_now = True)
def __str__(self):
return str(self.content)
ArticleSerializer
@api_view(['GET'])
def index2(request):
Article.objects.create(content="Sample Article")
articles = Article.objects.all()
serializer = ArticleSerializer(articles, many=True) #many=True : 여러개 가져옴
return Response(serializer.data)
@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, status=status.HTTP_201_CREATED)
else:
print(serializer.errors)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
article_view CRUD
@api_view(['GET', 'PUT', 'DELETE'])
def article_view(request, article_id):
if request.method == 'GET': #상세 페이지 불러오기
article = get_object_or_404(Article, article_id=article_id)
serializer = ArticleSerializer(article)
return Response(serializer.data)
elif request.method == "PUT": # 게시글 수정하기
article = get_object_or_404(Article, article_id=article_id)
serializer = ArticleSerializer(article, data=request.data) # (기존 데이터, 변경할 데이터)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
elif request.method == "DELETE": # 게시글 삭제하기
article = get_object_or_404(Article, article_id=article_id)
article.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
전체를 볼 수 있는 api는 /article/index/ 인데, 상세페이지를 불러오는 api는 article/int:article_id/ 인게 불편해서 수정해버림
urlpatterns = [
path('list/', views.list, name='list'),
path('list/<int:article_id>/', views.article_view, name='article_view'),
]
삭제