Django Rest Framework 入门指南

Django Rest Framework (DRF) is powerful, sophisticated, and surprisingly easy to use. It offers an attractive, web browseable version of your API, and the option of returning raw JSON. The Django Rest Framework provides powerful model serialization, display data using standard function based views, or get granular with powerful class based views for more complex functionality. All in a fully REST compliant wrapper.

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.

新建 App
startapp base
创建 models
# 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 database

** 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<pk>\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)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 162,710评论 4 376
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 68,839评论 2 308
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 112,295评论 0 255
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,776评论 0 223
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 53,198评论 3 297
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 41,074评论 1 226
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,200评论 2 322
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,986评论 0 214
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,733评论 1 250
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,877评论 2 254
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,348评论 1 265
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,675评论 3 265
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,393评论 3 246
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,209评论 0 9
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,996评论 0 201
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 36,212评论 2 287
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 36,003评论 2 280

推荐阅读更多精彩内容