一、官网快速实例

quickstart

# 安装 RESTful
pip install djangorestframework

二、序列化

models.py

from django.db import models

class Author(models.Model):
name = models.CharField(max_length=32, verbose_name="作者")
age = models.IntegerField(verbose_name="年龄")
def __str__(self):
return self.name class Publisher(models.Model):
name = models.CharField(max_length=32, verbose_name="出版社")
email = models.EmailField(verbose_name="邮箱")
address = models.CharField(max_length=128, verbose_name="地址")
def __str__(self):
return self.name class Book(models.Model):
title = models.CharField(max_length=32, verbose_name="书名")
price = models.DecimalField(max_digits=5, decimal_places=2, verbose_name="价格")
publish_date = models.DateField(verbose_name="出版日期")
# 与Publish建立一对多的关系,外键字段一般建立在多的一方
publisher = models.ForeignKey(to="Publisher", verbose_name="出版社")
# 与Author表建立多对多的关系,ManyToManyField通常设置在正向查询多的那一边,自动创建第三张表
authors = models.ManyToManyField(to="Author", verbose_name="作者")
def __str__(self):
return self.title

urls.py

from django.conf.urls import url
from appxx import views urlpatterns = [
url(r"^publishers/$", views.PublisherList.as_view()),
url(r"^publishers/(\d+)$", views.PublisherDetail.as_view()),
url(r"^books/$", views.BookList.as_view()),
url(r"^books/(\d+)$", views.BookDetail.as_view()),
]

views.py

铺垫:

from django.shortcuts import HttpResponse
from django.views import View
from appxx import models
from django.forms.models import model_to_dict
from django.core import serializers class PublisherList(View):
def get(self, request):
"""取数据""" # 方式一:
publisher_list = models.Publisher.objects.all().values("name", "email", "address")
return HttpResponse(publisher_list) # 方式二:
publisher_list = models.Publisher.objects.all()
temp = []
for obj in publisher_list:
temp.append(model_to_dict(obj))
return HttpResponse(temp) # 方式三:
publisher_list = models.Publisher.objects.all()
data = serializers.serialize("json", publisher_list)
return HttpResponse(data)
  
   def get(self, request):
     pass

RESTful 的 Serializer

Publisher表(没有一对多和多对多字段)

from appxx import models
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import serializers class PublisherSerializer(serializers.Serializer):
name = serializers.CharField(max_length=32)
email = serializers.EmailField()
address = serializers.CharField(max_length=128) def create(self, validated_data):
# 根据提供的验证过的数据创建并返回一个新的"Publisher"实例
return models.Publisher.objects.create(**validated_data) def update(self, instance, validated_data):
# 根据提供的验证过的数据更新并返回一个已经存在的"Publisher"实例
instance.name = validated_data.get("name", instance.name)
instance.email = validated_data.get("email", instance.email)
instance.address = validated_data.get("address", instance.address)
instance.save()
return instance class PublisherList(APIView):
def get(self, request):
publisher_list = models.Publisher.objects.all()
s = PublisherSerializer(publisher_list, many=True)
return Response(s.data) def post(self, request):
s = PublisherSerializer(data=request.data)
if s.is_valid():
s.save()
return Response(s.data)
return Response(s.errors) class PublisherDetail(APIView):
def get(self, request, pk):
publisher = models.Publisher.objects.filter(pk=pk).first()
s = PublisherSerializer(publisher)
return Response(s.data) def put(self, request, pk):
publisher = models.Publisher.objects.filter(pk=pk).first()
s = PublisherSerializer(publisher, data=request.data)
if s.is_valid():
s.save()
return Response(s.data)
return Response(s.errors) def delete(self, request, pk):
models.Publisher.objects.filter(pk=pk).delete()
return Response("删除成功")

RESTful 的 ModelSerializer

Book表(有一对多和多对多字段)

备注说明:ModelSerializer继承Serializer;如果一对多字段中有参数source,post提交数据时 --> 则需要重写save中的create方法;除此之外,对于多对多字段,如果使用下面的方法请求(get)数据,将会得到更直观的数据,但这里并没有解决post、put请求操作。

class BookSerializer(serializers.ModelSerializer):
class Meta:
model = models.Book
fields = "__all__" # fields = ("title", "price", "publish_date", "publisher", "authors") # 一对多,通过source="本张表一对多字段.关联的表的任一字段",即可获取到对应的数据;如果不写,则获取到的是pk值
publisher = serializers.CharField(source="publisher.name") # 多对多,通过source="本张表多对多字段.all",获取到的是 QuerySet 数据;如果不写,则获取到的是pk值
# authors = serializers.CharField(source="authors.all") # 多对多,还可以用下面的方法获取到关联的数据
# authors = serializers.SerializerMethodField() # def get_authors(self, obj): # 格式:get_多对多字段名(self, obj)
# temp = []
# for author in obj.authors.all():
# temp.append(author.name)
# return temp # 重写save中的create方法
def create(self, validated_data):
obj = models.Book.objects.create(
title=validated_data["title"],
price=validated_data["price"],
publish_date=validated_data["publish_date"],
publisher_id=validated_data["publisher"]["name"],
)
obj.authors.add(*validated_data["authors"])
return obj class BookList(APIView):
def get(self, request): # 获取书籍列表
book_list = models.Book.objects.all()
s = BookSerializer(book_list, many=True)
return Response(s.data) def post(self, request): # 新增书籍
s = BookSerializer(data=request.data)
if s.is_valid():
s.save() # 实际执行的是create()方法
return Response(s.data)
return Response(s.errors) class BookDetail(APIView):
def get(self, request, pk): # 获取某本书籍
book = models.Book.objects.filter(pk=pk).first()
s = BookSerializer(book)
return Response(s.data) def put(self, request, pk): # 修改某本书籍
book = models.Book.objects.filter(pk=pk).first()
s = BookSerializer(book, data=request.data)
if s.is_valid():
s.save() # 实际执行的是update()方法
return Response(s.data)
return Response(s.errors) def delete(self, request, pk): # 删除某本书籍
models.Book.objects.filter(pk=pk).delete()
return Response("删除成功")

超链接API:HyperlinkedModelSerializer(继承ModelSerializer)

官网内容

class BookSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = models.Book
fields = "__all__" publisher = serializers.HyperlinkedIdentityField(
view_name="publisher_detail",
lookup_field="publisher_id",
lookup_url_kwarg="pk"
) class BookList(APIView):
def get(self, request):
book_list = models.Book.objects.all()
s = BookSerializer(book_list, many=True, context={"request": request})
return Response(s.data) class BookDetail(APIView):
def get(self, request, pk):
book = models.Book.objects.filter(pk=pk).first()
s = BookSerializer(book, context={"request": request})
return Response(s.data)

urls.py部分:

from django.conf.urls import url
from appxx import views urlpatterns = [
url(r"^publishers/$", views.PublisherList.as_view(), name="publisher_list"),
url(r"^publishers/(?P<pk>\d+)/$", views.PublisherDetail.as_view(), name="publisher_detail"),
url(r"^books/$", views.BookList.as_view(), name="book_list"),
url(r"^books/(\d+)/$", views.BookDetail.as_view(), name="book_detail"),
]

则获取到的数据,相应字段将改为超链接:

三、使用mixins

# views.py
from appxx import models
from rest_framework import serializers
from rest_framework import mixins
from rest_framework import generics class BookSerializer(serializers.ModelSerializer):
class Meta:
model = models.Book
fields = "__all__" class BookList(mixins.ListModelMixin,
mixins.CreateModelMixin,
generics.GenericAPIView):
queryset = models.Book.objects.all()
serializer_class = BookSerializer def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs) def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs) class BookDetail(mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
generics.GenericAPIView):
queryset = models.Book.objects.all()
serializer_class = BookSerializer def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs) def put(self, request, *args, **kwargs):
return self.update(request, *args, **kwargs) def delete(self, request, *args, **kwargs):
return self.destroy(request, *args, **kwargs)
# urls.py
urlpatterns = [
url(r"^books/$", views.BookList.as_view(), name="book_list"),
url(r"^books/(?P<pk>\d+)/$", views.BookDetail.as_view(), name="book_detail"),
]

四、使用基于类的通用视图

# views.py
from appxx import models
from rest_framework import serializers
from rest_framework import generics class BookSerializer(serializers.ModelSerializer):
class Meta:
model = models.Book
fields = "__all__" class BookList(generics.ListCreateAPIView):
queryset = models.Book.objects.all()
serializer_class = BookSerializer class BookDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = models.Book.objects.all()
serializer_class = BookSerializer
# urls.py
urlpatterns = [
url(r"^books/$", views.BookList.as_view(), name="book_list"),
url(r"^books/(?P<pk>\d+)/$", views.BookDetail.as_view(), name="book_detail"),
]

五、ViewSet

使用ViewSet重构:

from appxx import models
from rest_framework import serializers
from rest_framework import viewsets class BookSerializer(serializers.ModelSerializer):
class Meta:
model = models.Book
fields = "__all__" class BookViewSet(viewsets.ModelViewSet):
queryset = models.Book.objects.all()
serializer_class = BookSerializer

将ViewSet明确绑定到URL:

from django.conf.urls import url
from appxx import views urlpatterns = [
url(r"^books/$", views.BookViewSet.as_view({
"get": "list",
"post": "create"}), name="book_list"),
url(r"^books/(?P<pk>\d+)/$", views.BookViewSet.as_view({
"get": "retrieve",
"put": "update",
"patch": "partial_update",
"delete": "destroy"}), name="book_detail"),
]

将URL整理一下:

from django.conf.urls import url
from appxx import views book_list = views.BookViewSet.as_view({
"get": "list",
"post": "create"})
book_detail = views.BookViewSet.as_view({
"get": "retrieve",
"put": "update",
"patch": "partial_update",
"delete": "destroy"}) urlpatterns = [
url(r"^books/$", book_list, name="book_list"),
url(r"^books/(?P<pk>\d+)/$", book_detail, name="book_detail"),
]

六、使用路由器

from django.conf.urls import url, include
from appxx import views
from rest_framework.routers import DefaultRouter router = DefaultRouter()
router.register(r"books", views.BookViewSet)
router.register(r"publishers", views.PublisherViewSet) urlpatterns = [
url(r"", include(router.urls)),
]

Django REST framework 初识的更多相关文章

  1. Django REST framework 自定义(认证、权限、访问频率)组件

    本篇随笔在 "Django REST framework 初识" 基础上扩展 一.认证组件 # models.py class Account(models.Model): &qu ...

  2. Vue+Django REST framework打造生鲜电商项目

    1-1 课程导学 2-1 Pycharm的安装和简单使用 2-2 MySQL和Navicat的安装和使用 2-3 Windows和Linux下安装Python2和Python3 2-4 虚拟环境的安装 ...

  3. 使用django rest framework

    django 刚接触,想做一些restful api , google了一下,发现有现成的框架.Django REST framework. 对使用做下记录: 安装 从http://django-re ...

  4. 利用 Django REST framework 编写 RESTful API

    利用 Django REST framework 编写 RESTful API Updateat 2015/12/3: 增加 filter 最近在玩 Django,不得不说 rest_framewor ...

  5. django rest framework 入门

    django rest framework 入门1-序列化 Serialization 分类: Python 2013-01-22 22:24 11528人阅读 评论(0) 收藏 举报 djangop ...

  6. django rest framework

    Django-Rest-Framework 教程: 4. 验证和权限 作者: Desmond Chen, 发布日期: 2014-06-01, 修改日期: 2014-06-02 到目前为止, 我们的AP ...

  7. django rest framework csrf failed csrf token missing or incorrect

    django rest framework csrf failed csrf token missing or incorrect REST_FRAMEWORK = { 'DEFAULT_AUTHEN ...

  8. Django REST Framework学习——Android使用REST方法访问Diango

    本文更应该叫做Android如何模拟浏览器访问Django服务器后台. 环境为: Android通过HttpClient访问服务器,从Django中获取json数据,解析显示在UI界面上. 问题为: ...

  9. 用Django Rest Framework和AngularJS开始你的项目

    Reference: http://blog.csdn.net/seele52/article/details/14105445 译序:虽然本文号称是"hello world式的教程&quo ...

随机推荐

  1. Localhost 回环IP 127.0.0.1

    LocalHost 127.0.0.1是一个保留地址,用于本地软件測试以及本地进程间通信, 也叫回环IP.回环地址.回送地址(loopback address).不管什么程序,一旦使 用回环IP发送数 ...

  2. 万维网 WWW (World Wide Web)

    万维网 WWW (World Wide Web)并非某种特殊的计算机网络.万维网是一个大规模的.联机式的信息储藏所.万维网用链接的方法能非常方便地从因特网上的一个站点访问另一个站点,从而主动地按需获取 ...

  3. 【POJ 1716】 Integer Intervals

    [题目链接] 点击打开链接 [算法] 差分约束系统 [代码] #include <algorithm> #include <bitset> #include <cctyp ...

  4. LuoguP3261 [JLOI2015]城池攻占

    题目描述 小铭铭最近获得了一副新的桌游,游戏中需要用 m 个骑士攻占 n 个城池.这 n 个城池用 1 到 n 的整数表示.除 1 号城池外,城池 i 会受到另一座城池 fi 的管辖,其中 fi &l ...

  5. eclipse的快捷键---调试

    1:查看类或接口的方法 Ctrl+T 2:debug调试查看信息 Ctrl+Shift+i 3:debug调试快捷键 (1):F11好像是重新运行debug. (2):F8直接输出结果.(3):F5单 ...

  6. thinkphp vender

    vender在thinkphp里面时引入系统的类库的意思,具体用法如下. Vendor('Classes.PHPExcel');表示引入vendor目录下的classes文件夹下面的phpexcel文 ...

  7. flex中align-content属性

    在flex弹性盒模型中align-content属性控制容器内多行在交叉轴上的排列方式 默认值:stretch 可用值: 属性值:flex-start 属性值:flex-end 属性值:center ...

  8. 实例化flask的参数及对app的配置

    Flask 是一个非常灵活且短小精干的web框架 , 那么灵活性从什么地方体现呢? 有一个神奇的东西叫 Flask配置 , 这个东西怎么用呢? 它能给我们带来怎么样的方便呢? 首先展示一下: from ...

  9. 2018.10.9 logstash启动慢的问题解决

    问题描述: 线上部署logstash 启动非常缓慢,达到了10分钟 问题解决 忍无可忍 网上资料基本都是熵过低导致jruby启动缓慢的问题,需要安装haveged 参考https://www.jian ...

  10. fcc 响应式框架Bootstrap 练习1

    需要通过添加下列代码到你的HTML开头来将Bootstrap添加到任意应用中: <link rel="stylesheet" href="//cdn.bootcss ...