写一个出版社的增删改查restful接口

models

 from django.db import models

 # Create your models here.

 from django.db import models

 # Create your models here.

 class Book(models.Model):
title = models.CharField(max_length=32)
price = models.IntegerField()
pub_date = models.DateField()
publish = models.ForeignKey("Publish")
authors = models.ManyToManyField("Author") def __str__(self):
return self.title def test(self):
return '' class Publish(models.Model):
name = models.CharField(max_length=32)
email = models.EmailField()
# def __str__(self):
# return self.name class Author(models.Model):
name = models.CharField(max_length=32)
age = models.IntegerField() def __str__(self):
return self.name

视图

 from django.shortcuts import render, HttpResponse
# Book相关操作
# Create your views here.
from api import models
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import serializers class BookSer(serializers.ModelSerializer):
class Meta:
model = models.Book
fields = "__all__" class List():
def list(self):
ret = self.ret.objects.all()
ser = self.book_ser(instance=ret, many=True)
return Response(ser.data) class Create():
def create(self, request):
back_msg = {'status': 0, 'data': None, 'msg': 'error happened'}
ser = BookSer(data=request.data)
if ser.is_valid():
ser.save()
back_msg['data'] = ser.data
back_msg['status'] = 1
back_msg['msg'] = 'create success'
return Response(back_msg) class Book(APIView, List, Create):
ret = models.Book
book_ser = BookSer def get(self, request):
return self.list() def post(self, request):
return self.create(request) class BookDetail(APIView):
def get(self, request, pk):
ret = models.Book.objects.filter(pk=pk).first()
ser = BookSer(instance=ret, many=False)
return Response(ser.data) def put(self, request, pk):
ret = models.Book.objects.filter(pk=pk).first()
ser = BookSer(instance=ret, data=request.data)
if ser.is_valid():
ser.save()
return Response(ser.data) def delete(self, request, pk):
models.Book.objects.filter(pk=pk).delete()
return HttpResponse('already deleted')

mixin类和generice类编写视图

 from rest_framework.mixins import CreateModelMixin,RetrieveModelMixin,ListModelMixin,UpdateModelMixin,DestroyModelMixin
from rest_framework.generics import GenericAPIView
class PublishView(ListModelMixin,CreateModelMixin,GenericAPIView):
queryset=models.Publish.objects.all()
serializer_class=PublishSerializers def get(self, request):
return self.list(request) def post(self, request):
return self.create(request) class PublishDetailView(RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin,GenericAPIView):
queryset=models.Publish.objects.all()
serializer_class=PublishSerializers
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)

使用generics 下ListCreateAPIView,RetrieveUpdateDestroyAPIView

from rest_framework.generics import ListCreateAPIView,RetrieveUpdateDestroyAPIView
class PublishView(ListCreateAPIView):
queryset=models.Publish.objects.all()
serializer_class=PublishSerializers class PublishDetailView(RetrieveUpdateDestroyAPIView):
queryset=models.Publish.objects.all()
serializer_class=PublishSerializers

使用ModelViewSet

路由

 url(r'^publish/$', views.PublishView.as_view({'get':'list','post':'create'})),
url(r'^publish/(?P<pk>\d+)/$', views.PublishView.as_view({'get':'retrieve','put':'update','delete':'destroy'})),

视图

from rest_framework.viewsets import ModelViewSet
class PublishView(ModelViewSet):
queryset=models.Publish.objects.all()
serializer_class=PublishSerializers

rest_framework之视图的更多相关文章

  1. Django的rest_framework的视图之基于通用类编写视图源码解析

    我们上一篇博客讲解了如何使用mixins类实现rest_framework的视图,但是其中有很多的冗余的代码,我们这边在来优化一下 1.queryset的视图函数 首先看下对queryset操作的视图 ...

  2. rest_framework中视图相关

    模型类的定义 # 定义图书模型类BookInfo class BookInfo(models.Model): btitle = models.CharField(max_length=20, verb ...

  3. Django的rest_framework的视图之基于ModelViewSet视图源码解析

    前言 今天一直在整理Django的rest_framework的序列化组件,前面一共写了2篇博客,前面的博客给的方案都是一个中间的状态的博客,其中有很多的冗余的代码,如果有朋友不清楚,可以先看下我前面 ...

  4. Django的rest_framework的视图之Mixin类编写视图源码解析

    Mixin类编写视图 我们这里用auther表来做演示,先为auther和autherdetail写2个url url(r'^autherdetail/(?P<id>\d+)', view ...

  5. Rest_Framework的视图与路由

    视图与路由 drf除了在数据序列化部分简写代码以外,还在视图中提供了简写操作.所以在django原有的django.views.View类基础上,drf封装了多个子类出来提供给我们使用. Django ...

  6. rest_framework之视图及源码剖析

    最初形态(工作中可能会使用) 引子 Django的CBV我们应该都有所了解及使用,大体概括一下就是通过定义类并在类中定义get post put delete等对应于请求方法的方法,当请求来的时候会自 ...

  7. rest_framework 之视图

    1. 继承ModelSerilizer,直接指定要序列化的表模型 MySerializers.py from app import models # 继承ModelSerilizer,直接指定要序列化 ...

  8. rest_framework的视图组件继承过哪些类?

  9. django rest_framework入门四-类视图APIView

    上节,我们使用函数视图,用了@api_view装饰器来修饰,这一节,我们介绍类视图APIView,显然,类视图更符合面向对象的原则. 1.使用类视图APIView重写API 类视图APIView,取代 ...

随机推荐

  1. BZOJ1861:[ZJOI2006]书架

    浅谈\(splay\):https://www.cnblogs.com/AKMer/p/9979592.html 浅谈\(fhq\)_\(treap\):https://www.cnblogs.com ...

  2. Nuget:template

    ylbtech-Nuget: 1.返回顶部   2.返回顶部   3.返回顶部   4.返回顶部   5.返回顶部     6.返回顶部   作者:ylbtech出处:http://ylbtech.c ...

  3. appium+python 快速给真机安装app

    #coding=utf-8from appium import webdriverfrom time import sleepimport os,time,unittest '''给手机快速装app的 ...

  4. Python文件运行时报TabError: inconsistent use of tabs and spaces in indentation

    1. 问题描述 Python文件运行时报TabError: inconsistent use of tabs and spaces in indentation 2. 问题原因 tab 和 space ...

  5. 使用Axis2方式发布webService的三种方式

    1.Axis2的下载和安装 首先可以下载如下两个zip包:axis2-1.6.1-bin.zipaxis2-1.6.1-war.zip其中 axis2-1.6.1-bin.zip文件中包含了Axis2 ...

  6. centos6.5安装FTP服务器

    1.检测是否安装了FTP rpm -q vsftpd 2.安装ftp yum install vsftpd 3.完成ftp安装后,将 /etc/vsftpd/user_list 和 /etc/vsft ...

  7. Object有哪些公用的方法?

    Object是所有类的父类,任何类都默认继承Object. public class Demo { public static void main(String[] args) { Object ob ...

  8. 远程抓取win7 的用户登录时间

    protected void Page_Load(object sender, EventArgs e) { InvokeSystemPS("query user /server:192.1 ...

  9. JS中map list 数组的迭代

    后台传给前台一个map 前台如何迭代呢 $.post("getSys.jhtml", function(data){ var temp = ""; $.each ...

  10. E20190523-h

    evaluate v. 估计; 评价; 评估; substantial  adj. 大量的; 价值巨大的; 重大的; 大而坚固的; 结实的; 牢固的; portion n. 部分; (食物的) 一份, ...