-
[Django] Django REST API (3) - REST API CRUDPhthon/Django 2019. 12. 28. 21:35728x90
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'Phthon > Django' 카테고리의 다른 글
[Django] Django란? (1) 2020.06.30 [Django] REST API (4) - Frontend 연동 (0) 2020.01.01 [Django] Django REST API (2) - REST API 작성 (0) 2019.12.26 [Django] Django REST API (1) - 개발환경 설정 (0) 2019.12.26 [Django] no migrations to apply 참고 (0) 2019.10.27