PROJECTS

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

nicesugi 2022. 6. 25. 02:59

🌱 Github

https://github.com/nicesugi/joo_test


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

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

 

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

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

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

* DRF serializer μ΄μš©ν•œ μ½”λ“œ

[μ½”λ¦° μΌμ§€πŸ‘©πŸ»‍πŸ’»/django] - DRF serializer μ΄μš©ν•œ [κ²Œμ‹œκΈ€ 쑰회, μž‘μ„±, μˆ˜μ •, μ‚­μ œ ] μ΄ˆκ°„λ‹¨ μ½”λ“œ


Django [κ²Œμ‹œκΈ€ μ‘°νšŒ, μž‘μ„±, μˆ˜μ •, μ‚­μ œ ] μ΄ˆκ°„단 μ½”λ“œ

class PostView(APIView):
# κ²Œμ‹œκΈ€ 쑰회
    def get(self, request):
    # 1 μž‘μ„±μžμ˜ κ²Œμ‹œκΈ€λ§Œ! 쑰회
        user = request.user
        print(user)
        posts = Post.objects.filter(user=user).values('user', 'content')
        return Response ({'post': posts})

class PostView(APIView):
# κ²Œμ‹œκΈ€ 쑰회               
    # 2 전체 κ²Œμ‹œκΈ€ 쑰회
        posts = Post.objects.values('user', 'content') 
        return Response ({'post': posts})

values μ„€μ •

# values() > id, user, content μ „λΆ€
# values('user', 'content') > user, content λ‚΄κ°€ μ›ν•˜λŠ” κ²ƒλ§Œ


# κ²Œμ‹œκΈ€ μž‘μ„±
    def post(self, request):
        user = request.user
        content = request.data.get('content', '')
        
        content, created = Post.objects.get_or_create(
            content = content
            )
        if created:
            content.user = user
            content.save()
            print(f'content.id: {content}')
        return Response({"message":"κ²Œμ‹œκΈ€ μž‘μ„± 성곡"})

# κ²Œμ‹œκΈ€ μˆ˜μ •
    def put(self, request, obj_id):
        fix_content = Post.objects.get(id=obj_id)
        fix_content.content = request.data.get('content')
        fix_content.save()

# κ²Œμ‹œκΈ€ μ‚­μ œ
    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/models.py

λ°˜μ‘ν˜•