PROJECTS

DRF serializer μ΄μš©ν•œ [κ²Œμ‹œκΈ€ 쑰회, μž‘μ„±, μˆ˜μ •, μ‚­μ œ ] μ΄ˆκ°„λ‹¨ μ½”λ“œ

nicesugi 2022. 6. 23. 00:35

🌱 Github

https://github.com/nicesugi/joo_test


μŠ€ν„°λ””μ—μ„œ DRF λ―Έλ‹ˆ νƒ€μž„μ–΄νƒμ„ ν–ˆμ—ˆλ‹€.

.. 2탄도 ν•΄μ•Όν•˜λŠ”λ°, λ„μ €νžˆ ν˜„μž¬ μƒν™©μ—μ„œ 이해가 μ•ˆκ°€κΈΈλž˜ λ‹€μŒκΈ°νšŒλ₯Ό 노리고 있음.

 

κ³΅λΆ€ν•˜λ‹€κ°€ Django λ°”λ‹λΌμ½”λ“œλž‘ 같이 λΉ„κ΅ν•΄μ„œ μž‘μ„±ν•΄λ„ μ’‹κ² λ‹€λŠ” 생각에

μž₯고와 DRF λ‘˜μ˜ μ½”λ“œλ₯Ό 같은 쑰건?μ—μ„œ μž‘μ„±ν•΄λ³΄μžλΌλŠ” 생각에 μž‘μ„±ν•˜κ²Œ λ˜μ—ˆλ‹€.

* status μ½”λ“œλŠ” μž‘μ„±ν•˜μ§€ μ•ŠμŒ

* μ•„λž˜μ— modelκ³Ό serializer μ½”λ“œλ„ 첨뢀됨

DRF serializer μ΄μš©ν•˜μ—¬ [κ²Œμ‹œκΈ€ 쑰회, μž‘μ„±, μˆ˜μ •, μ‚­μ œ ] μ½”λ“œ μž‘μ„±ν•˜κΈ°

class PostView(APIView):
# κ²Œμ‹œκΈ€ 쑰회
    def get(self, request):
# 1 μž‘μ„±μžμ˜ κ²Œμ‹œκΈ€λ§Œ! 쑰회
        print(request.data)
        user = request.user
        
        return Response(UserSerializer(user).data)

class PostView(APIView):
# κ²Œμ‹œκΈ€ 쑰회
    def get(self, request):
# 2 전체 κ²Œμ‹œκΈ€ 쑰회
        posts = Post.objects.all()
        serialized_data = PostSerializer(posts, many=True).data
        
        return Response(serialized_data)

class PostView(APIView):
	def post(self, request):
# κ²Œμ‹œκΈ€ μž‘μ„±
        request.data['user'] = request.user.id
        post_serializer = PostSerializer(data=request.data)
        print(post_serializer)
        
        if post_serializer.is_valid():
            post_serializer.save()
            return Response(post_serializer.data)
            
        return Response(post_serializer.errors)

class PostView(APIView):
	def put(self, request, obj_id):
# κ²Œμ‹œκΈ€ μˆ˜μ •
        content = Post.objects.get(id=obj_id)
        content_serializer = PostSerializer(content, data=request.data, context={"request": request})
        print(f'content_serializer: {(content_serializer)}')
        
        if content_serializer.is_valid():
            content_serializer.save()
            return Response({"message": "κ²Œμ‹œκΈ€ μˆ˜μ • 성곡"})
            
        return Response({"message": "κ²Œμ‹œκΈ€ μˆ˜μ • μ‹€νŒ¨"})

class PostView(APIView):
    def delete(self, request, obj_id):
# κ²Œμ‹œκΈ€ μ‚­μ œ
    	user = request.user
        content = Post.objects.get(id=obj_id)
        
        if user:
            content.delete()
            return Response({"message": "μ‚­μ œ 성곡"})
            
        return Response({"message": "μ‚­μ œ μ‹€νŒ¨"})

 

 

πŸ”½ Post/serializers.py

 

πŸ”½ User/serializers.py

 

πŸ”½ Post/models.py

 

πŸ”½ User/models.py

 

λ°˜μ‘ν˜•