Django REST framework 初识
一、官网快速实例
# 安装 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 初识的更多相关文章
- Django REST framework 自定义(认证、权限、访问频率)组件
本篇随笔在 "Django REST framework 初识" 基础上扩展 一.认证组件 # models.py class Account(models.Model): &qu ...
- Vue+Django REST framework打造生鲜电商项目
1-1 课程导学 2-1 Pycharm的安装和简单使用 2-2 MySQL和Navicat的安装和使用 2-3 Windows和Linux下安装Python2和Python3 2-4 虚拟环境的安装 ...
- 使用django rest framework
django 刚接触,想做一些restful api , google了一下,发现有现成的框架.Django REST framework. 对使用做下记录: 安装 从http://django-re ...
- 利用 Django REST framework 编写 RESTful API
利用 Django REST framework 编写 RESTful API Updateat 2015/12/3: 增加 filter 最近在玩 Django,不得不说 rest_framewor ...
- django rest framework 入门
django rest framework 入门1-序列化 Serialization 分类: Python 2013-01-22 22:24 11528人阅读 评论(0) 收藏 举报 djangop ...
- django rest framework
Django-Rest-Framework 教程: 4. 验证和权限 作者: Desmond Chen, 发布日期: 2014-06-01, 修改日期: 2014-06-02 到目前为止, 我们的AP ...
- django rest framework csrf failed csrf token missing or incorrect
django rest framework csrf failed csrf token missing or incorrect REST_FRAMEWORK = { 'DEFAULT_AUTHEN ...
- Django REST Framework学习——Android使用REST方法访问Diango
本文更应该叫做Android如何模拟浏览器访问Django服务器后台. 环境为: Android通过HttpClient访问服务器,从Django中获取json数据,解析显示在UI界面上. 问题为: ...
- 用Django Rest Framework和AngularJS开始你的项目
Reference: http://blog.csdn.net/seele52/article/details/14105445 译序:虽然本文号称是"hello world式的教程&quo ...
随机推荐
- DDM实践:数据库秒级平滑扩容方案
本文部分内容节选自华为云帮助中心的分布式数据库中间件(DDM)服务的产品介绍 背景 随着业务增长,逻辑库存储空间不足,并发压力较大. 解决方案 此时可对DDM实例逻辑库进行平滑扩容,通过增加RDS实例 ...
- leetCode 60.Permutation Sequence (排列序列) 解题思路和方法
The set [1,2,3,-,n] contains a total of n! unique permutations. By listing and labeling all of the p ...
- [转]Dialog
在Android开发中,我们经常会需要在Android界面上弹出一些对话框,比如询问用户或者让用户选择.这些功能我们叫它Android Dialog对话框,在我们使用Android的过程中,我归纳了一 ...
- P3202 [HNOI2009]通往城堡之路 神仙题
这个题不是坑人吗...写个tarjan标签,然后拿这么个神仙题来搞...代码有点看不懂,有兴趣的可以去洛谷题解区看看,懒得想了. 题干: 题目描述 听说公主被关押在城堡里,彭大侠下定决心:不管一路上有 ...
- bzoj2125 最短路——仙人掌两点间距离
题目:https://www.lydsy.com/JudgeOnline/problem.php?id=2125 仙人掌!模仿 lyd 的代码写的,也算是努力理解了: 主要分成 lca 在环上和不在环 ...
- codeforces 764D
脑洞 很早以前没有补掉的题目 四色问题肯定使有解的,然后就是怎么构造.注意到边长是奇数,那么我们就可以分类,按左上角坐标的奇偶性分类,正好对应四种颜色.因为当两个矩形左上角横纵坐标奇偶性不同时,那么肯 ...
- BigInteger、BigDecimal类的使用详解
我们都知道在java里边long算是存储长度比较大的了,但是如果有很大的数我们应该怎么处理呢,不用怕,java还为我们准备了一个BigInteger的类,那么这个类到底能存储多大的数呢,这个一时还真不 ...
- setjmp和longjmp函数
关于setjmp函数和longjmp函数有话要说,是UNIX高级环境变成看到了10.10信号那章用到了,研究一下,这里作为补充. setjmp(jmp_buf env_buf) 函数可以将当前的运行环 ...
- mysql数据库存储的引擎和数据类型
一.查看支持的存储引擎 SHOW ENGINES \G; 或者 SHOW VARIABLES LIKE 'have%'; 二.安装版mysql的默认引擎是InnoDB,免安装版默认引擎是MyISAM ...
- Spring Cloud (4) 服务消费者-Feign
Spring Cloud Feign Spring Cloud Feign 是一套基于Netflix Feign实现的声明式服务调用客户端.它使得编写Web服务客户端变得更加简单,我们只需要创建接口并 ...