ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Django] Django REST API (3) - REST API CRUD
    Phthon/Django 2019. 12. 28. 21:35
    728x90

    1. R(Post List)

    # restful/serializers.py
    
    from rest_framework import serializers
    from .models import posts
    
    class postsListSerializer(serializers.ModelSerializer):
        class Meta:
            model = posts #모델 설정
            fields = ('id', 'title', 'content', 'writer') #필드 설정
    restful/views.py
    
    from rest_framework import generics
    from .serializers import *
    from .models import posts
    
    class postsList(generics.ListAPIView):
        queryset = posts.objects.all()
        serializer_class = postsListSerializer
    restful/urls.py
    
    from django.conf.urls import url,include
    from . import views
    
    urlpatterns = [
        url('list/$', views.postsList.as_view(), name='postsList'),
    ]

     

    실행결과

     

     

    2. R(Detail)

     

    # restful/serializers.py 에 추가
    
    class postsDetailSerializer(serializers.ModelSerializer):
        class Meta:
            model = posts #모델 설정
            fields = ('id', 'title', 'content', 'writer') #필드 설정
    # restful/views.py 에 추가
    
    class postsDetail(generics.RetrieveAPIView):
        lookup_field = 'id'
        queryset = posts.objects.all()
        serializer_class = postsDetailSerializer
    # restful/urls.py
    
    from django.conf.urls import url,include
    from . import views
    
    urlpatterns = [
        url('list/$', views.postsList.as_view(), name='postsList'),
        url('list/(?P<id>\d+)/$', views.postsDetail.as_view(), name='postsDetail'), #detail url
    ]

    실행결과

     

     

    3. U(Update)

    # restful/views.py 에 추가
    
    class postsUpdate(generics.UpdateAPIView):
        lookup_field = 'id'
        queryset = posts.objects.all()
        serializer_class = postsListSerializer
    # restful/urls.py 의 urlpatterns에 추가
    
    url('list/(?P<id>\d+)/update$', views.postsUpdate.as_view(), name='postsUpdate'),

     

    4. D(Delete)

    # restful/views.py 에 추가
    
    class postsDelete(generics.DestroyAPIView):
        lookup_field = 'id'
        queryset = posts.objects.all()
        serializer_class = postsListSerializer
    # restful/urls.py 의 urlpatterns에 추가
    
    url('list/(?P<id>\d+)/delete$', views.postsDelete.as_view(), name='postsDelete'),

     

    5. C(Create)

     

    # restful/serializers.py 에 추가
    
    class postsCreateSerializer(serializers.ModelSerializer):
        class Meta:
            model = posts #모델 설정
            fields = ('title', 'content', 'writer') #필드 설정
    # restful/views.py
    
    class postsCreate(generics.CreateAPIView):
        queryset = posts.objects.all()
        serializer_class = postsCreateSerializer
    # restful/urls.py 의 urlpatterns에 추가
    
    url('list/create/$', views.postsCreate.as_view(), name='postsCreate'),

     

    728x90
Designed by Tistory.