(Model)Form vs (Model)Serializer
Django | Djnago Rest Framework |
Form/ModelForm | Serializer/ModelSerializer |
Model로부터 Field 읽어옴 | |
유효성 검사 | |
HTML Form 생성 | JSON 문자열 생성 |
django와 django rest framework 설치
$ pip install django
$ pip install djangorestframework
settings.py
# INSTALLED_APPS에 등록
'rest_framework'
models.py
from django.db import models
# Create your models here.
class Post(models.Model):
title = models.CharField(max_length=100)
body = models.TextField()
$ python manage.py makemigrations
$ python manage.py migrate
serializer.py
from .models import Post
from rest_framework import serializers
class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
# fields = '__all__'
fields = ('id', 'title', 'body') # id는 pk값과 동일한 기능
read_only_fields = ('title',) # 리스트도 가능하지만 튜플 사용을 권장함
views.py
from rest_framework import viewsets
from .models import Post
from .serializer import PostSerializer
# CBV
class PostViewSet(viewsets.ModelViewSet):
queryset = Post.objects.all()
serializer_class = PostSerializer
urls.py
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from . import views
# django rest framework -> router -> url
router = DefaultRouter()
router.register('post', views.PostViewSet)
urlpatterns = [
path('', include(router.urls)),
]
'Server > django' 카테고리의 다른 글
[Django] Pagination (0) | 2020.05.25 |
---|---|
[Django] View of DRF ( Django Rest Framework ) (0) | 2020.05.04 |
[Django] REST Architecture (0) | 2020.04.28 |
[Django] JSON, Http Request & Method, Httpie (0) | 2020.04.23 |
[Django] CRUD (0) | 2020.04.16 |