Django Rest Framework 시작 설명서
Working With Serialization
One powerful feature of the Django Rest Framework is the built in model serialization it offers. With just a few lines of code you can compose powerful representations of your data that can be delivered in a number of formats.
새 Apps
startapp base
모델 만들기
# base/models.py
# -*- coding:utf-8 -*-
from django.db import models
class Author(models.Model):
first_name = models.CharField(max_length=200)
last_name = models.CharField(max_length=200)
def __unicode__(self):
return '{} {}'.format(self.first_name, self.last_name)
class Book(models.Model):
title = models.CharField(max_length=200)
isbn = models.CharField(max_length=20)
author = models.ForeignKey(Author, related_name='books')
def __unicode__(self):
return self.title
SQLite 데이터베이스에 데이터 추가
** Author **
1 Andy Matthews
2 China Mieville
** Book **
1 jQuery Mobile Web Development Essentials 1849517266 1
2 jQuery Mobile Web Development Essentials 1849517266 2
3 Railsea 0345524535 2
```
##### serializer
```
# base/serializers.py
# -*- coding:utf-8 -*-
from rest_framework import serializers
from .models import Author
class AuthorSerializer(serializers.ModelSerializer):
"""
Serializing all the Authors
"""
class Meta:
model = Author
fields = ('id', 'first_name', 'last_name')
```
##### shell
```
>>> from base.models import Author
>>> from base.serializers import AuthorSerializer
>>> author = Author.objects.get(pk=1)
>>> serialized = AuthorSerializer(author)
>>> serialized.data
{'first_name': u'Andy', 'last_name': u'Matthews', 'id': 1}
```
##### Web Browseable API
```
# base/views.py
# -*- coding:utf-8 -*-
from rest_framework.generics import ListAPIView
from .models import Author
from .serializers import AuthorSerializer
class AuthorView(ListAPIView):
"""
Returns a list of all authors.
"""
queryset = Author.objects.all()
serializer_class = AuthorSerializer
```
```
# -*- coding:utf-8 -*-
from django.conf.urls import url
from .views import AuthorView
urlpatterns = [
url(r'^authors/$', AuthorView.as_view(), name='author-list'),
]
```
:http://127.0.0.1:8000/api/authors/
![](http://upload-images.jianshu.io/upload_images/2733312-11835c4d24b01f98.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
#### Giving the Authors Some Books!
`AuthorSerializer` `BookSerializer`:
```
class BookSerializer(serializers.ModelSerializer):
"""
Serializing all the Books
"""
class Meta:
model = Book
fields = ('id', 'title', 'isbn')
```
`AuthorSerializer`:
```
class AuthorSerializer(serializers.ModelSerializer):
"""
Serializing all the Authors
"""
books = BookSerializer(many=True)
class Meta:
model = Author
fields = ('id', 'first_name', 'last_name', 'books')
```
:http://127.0.0.1:8000/api/authors/
![](http://upload-images.jianshu.io/upload_images/2733312-0fc64cf2ab12aeb0.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
#### CRUD
** base/serializers.py **
```
# -*- coding:utf-8 -*-
from rest_framework import serializers
from rest_framework.generics import get_object_or_404
from .models import Author, Book
class BookSerializer(serializers.ModelSerializer):
"""
Serializing all the Books
"""
book_id = serializers.CharField(source='id', read_only=True) # the source allows you to explicitly name it something else when returning it to the end user.
author_id = serializers.IntegerField(source='author.id', read_only=True)
search_url = serializers.SerializerMethodField() # Use SerializerMethodField to Create Custom Properties
def get_search_url(self, obj):
return "http://www.isbnsearch.org/isbn/{}".format(obj.isbn)
class Meta:
model = Book
fields = ('book_id', 'title', 'isbn', 'author_id', 'search_url')
class AuthorSerializer(serializers.ModelSerializer):
"""
Serializing all the Authors
"""
id = serializers.ReadOnlyField()
books = BookSerializer(many=True)
def update(self, instance, validated_data):
instance.first_name = validated_data.get('first_name', instance.first_name)
instance.last_name = validated_data.get('last_name', instance.last_name)
instance.save()
for data in validated_data.pop('books'):
book = get_object_or_404(Book, pk=data.get('id'))
book.title = data.get('title')
book.isbn = data.get('isbn')
book.search_url = data.get('search_url')
book.save()
return instance
class Meta:
model = Author
fields = ('id', 'first_name', 'last_name', 'books')
```
** base/views.py **
```
# -*- coding:utf-8 -*-
from rest_framework.generics import ListCreateAPIView, RetrieveAPIView, get_object_or_404
from rest_framework.response import Response
from rest_framework import status
from .models import Author, Book
from .serializers import AuthorSerializer, BookSerializer
class AuthorView(ListCreateAPIView):
"""
Returns a list of all authors.
"""
queryset = Author.objects.all()
serializer_class = AuthorSerializer
def post(self, request, *args, **kwargs):
data_dict = request.data
books_data = data_dict.pop('books')
author, created = Author.objects.get_or_create(**data_dict)
if created:
for data in books_data:
Book.objects.create(author=author, **data)
else:
status_code = status.HTTP_406_NOT_ACCEPTABLE
return Response({'code': status_code, 'msg': ' '}, status=status_code)
status_code = status.HTTP_200_OK
return Response({'code': status_code, 'msg': ' '}, status=status_code)
class AuthorInstanceView(RetrieveAPIView):
"""
Returns a single author.
Also allows updating and deleting
"""
serializer_class = AuthorSerializer
def get_queryset(self):
return Author.objects.filter(pk=self.kwargs['pk'])
def get_object(self):
return get_object_or_404(self.get_queryset(), pk=self.kwargs['pk'])
def delete(self, request, *args, **kwargs):
author = self.get_object()
author.delete()
# 204(No Content) , ,
status_code = status.HTTP_204_NO_CONTENT
return Response({'code': status_code, 'msg': ' '}, status=status_code)
def put(self, request, *args, **kwargs):
author = self.get_object()
serializer = AuthorSerializer(author, data=request.data)
if serializer.is_valid():
serializer.update(author, request.data)
return Response(serializer.data)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class BookView(ListCreateAPIView):
"""
Returns a list of all books.
"""
queryset = Book.objects.all()
serializer_class = BookSerializer
```
** base/urls.py **
```
# -*- coding:utf-8 -*-
from django.conf.urls import url
from .views import AuthorView, AuthorInstanceView, BookView
urlpatterns = [
url(r'^authors/$', AuthorView.as_view(), name='author-list'),
url(r'^authors/(?P\d+)/$', AuthorInstanceView.as_view(), name='author-instance'),
url(r'^books/$', BookView.as_view(), name='book-list'),
]
```
** urls.py **
```
from django.conf.urls import include, url
from base import urls as base_urls
urlpatterns = [
url(r'^api/', include(base_urls)),
]
```
** **
![](http://upload-images.jianshu.io/upload_images/2733312-274b4ab28c74d7b9.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
![](http://upload-images.jianshu.io/upload_images/2733312-2d184ce0ba818c15.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
![](http://upload-images.jianshu.io/upload_images/2733312-867d95a470f621b3.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.