Article ↔ Comment 1:N Model Relation에서의 Serialization 실행!
읽기 전용 필드를 설정
read_only_fields
를 사용해서 comment가 달릴 article의 정보는 따로 받아올거라는 정의를 내리며 유효성검증에서 통과하게끔 만들자!
# ./articles/serializers.py
class CommentSerializer(serializers.ModelSerializer):
class Meta:
model = Comment
# 사용자에게 보여줄 필드와 받을 필드 신경쓰자
fields = ('id','content','article')
read_only_fields=('article',)
# ./articles/urls.py
urlpatterns = [
path('',views.article_list_create,name='article_list_create'), #GET POST를 받을 수 있다.
path('<int:article_pk>/',views.article_detail_update_delete,name='article_detail_update_delete'),
path('<int:article_pk>/comments/',views.comment_list_create,name='comment_list_create'),
path('<int:article_pk>/comments/<int:comment_pk>/',views.comment_detail_update_delete,name='comment_detail_update_delete'),
]
Article 하나에 해당하는 댓글 생성 및 하위 댓글들 불러오기
serializer.save(article=article)
를 통해 request.data
에서 포함되 않은 정보인 article의 정보를 넣어줍시다!# ./articles/views.py
@api_view(['GET','POST'])
def comment_list_create(request,article_pk):
article = get_object_or_404(Article,pk=article_pk)
'''
POST /api/v1/articles/{article_pk}/comments/
GET /api/v1/articles/{article_pk}/comments/
'''
if request.method=="POST":
serializer = CommentSerializer(data=request.data) #1
if serializer.is_valid(raise_exception=True): #2
serializer.save(article=article)
return Response(serializer.data,status=status.HTTP_201_CREATED)
elif request.method=='GET':
comments = article.comment_set.all()
serializer=CommentSerializer(comments,many=True)
return Response(serializer.data)
POST
GET
article_pk가 6인 article에서의 댓글 리스트 가져오기
댓글 데이터 불러오기 업데이트 삭제
# ./articles/views.py
@api_view(['GET','PUT','DELETE'])
def comment_detail_update_delete(request,article_pk,comment_pk):
comment = get_object_or_404(Comment,pk=comment_pk)
'''
GET /api/v1/articles/{article_pk}/comments/{comment_pk}
PUT /api/v1/articles/{article_pk}/comments/{comment_pk}
DELETE /api/v1/articles/{article_pk}/comments/{comment_pk}
'''
if request.method=='GET':
serializer = CommentSerializer(comment
return Response(serializer.data)
elif request.method =='DELETE':
comment.delete()
return Response({'comment_pk':comment_pk},status=status.HTTP_204_NO_CONTENT)
elif request.method=='PUT':
serializer=CommentSerializer(data=request.data,instance=comment)
if serializer.is_valid(raise_exception=True):
serializer.save()
return Response(serializer.data,status=status.HTTP_200_OK)
댓글 detail 불러오기
댓글 업데이트
댓글삭제
Thanks for the blog loaded with so many information. Stopping by your blog helped me to get what I was looking for. บาคาร่า