-
[Django] Django REST API (2) - REST API 작성Phthon/Django 2019. 12. 26. 20:27728x90
1. Model 생성
#/restful/models.py from django.db import models class posts(models.Model): title = models.CharField(max_length=100) content = models.CharField(max_length=300) writer = models.CharField(max_length=100) def __str__(self): return self.title
python manage.py makemigrations
python manage.py migrate
2. Serializer 생성
/restful/serializers.py from rest_framework import serializers from .models import posts class postsSerializer(serializers.ModelSerializer): class Meta: model = posts #모델 설정 fields = ('title', 'content', 'writer') #필드 설정
3. views.py
# /restful/views.py from django.shortcuts import render from rest_framework import viewsets from .serializers import postsSerializer from .models import posts class postsMain(viewsets.ModelViewSet): queryset = posts.objects.all() serializer_class = postsSerializer
4. urls.py
#/restStudy/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('restful.urls')), ]
#/restful/urls.py from django.conf.urls import url,include from rest_framework import routers from restful.views import postsMain router = routers.DefaultRouter() router.register('posts', postsMain) urlpatterns = [ url('/', include(router.urls)), ]
5. 실행
728x90'Phthon > Django' 카테고리의 다른 글
[Django] REST API (4) - Frontend 연동 (0) 2020.01.01 [Django] Django REST API (3) - REST API CRUD (0) 2019.12.28 [Django] Django REST API (1) - 개발환경 설정 (0) 2019.12.26 [Django] no migrations to apply 참고 (0) 2019.10.27 [Django] Django HttpResponse list return (0) 2019.09.24