rest_framework之视图

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

models

 1 from django.db import models
 2 
 3 # Create your models here.
 4 
 5 
 6 from django.db import models
 7 
 8 
 9 # Create your models here.
10 
11 
12 class Book(models.Model):
13     title = models.CharField(max_length=32)
14     price = models.IntegerField()
15     pub_date = models.DateField()
16     publish = models.ForeignKey("Publish")
17     authors = models.ManyToManyField("Author")
18 
19     def __str__(self):
20         return self.title
21 
22     def test(self):
23         return '555'
24 
25 
26 class Publish(models.Model):
27     name = models.CharField(max_length=32)
28     email = models.EmailField()
29     # def __str__(self):
30     #     return self.name
31 
32 
33 class Author(models.Model):
34     name = models.CharField(max_length=32)
35     age = models.IntegerField()
36 
37     def __str__(self):
38         return self.name
View Code

 

视图

 1 from django.shortcuts import render, HttpResponse
 2 # Book相关操作
 3 # Create your views here.
 4 from api import models
 5 from rest_framework.response import Response
 6 from rest_framework.views import APIView
 7 from rest_framework import serializers
 8 
 9 
10 class BookSer(serializers.ModelSerializer):
11     class Meta:
12         model = models.Book
13         fields = "__all__"
14 
15 
16 class List():
17     def list(self):
18         ret = self.ret.objects.all()
19         ser = self.book_ser(instance=ret, many=True)
20         return Response(ser.data)
21 
22 
23 class Create():
24     def create(self, request):
25         back_msg = {'status': 0, 'data': None, 'msg': 'error happened'}
26         ser = BookSer(data=request.data)
27         if ser.is_valid():
28             ser.save()
29             back_msg['data'] = ser.data
30             back_msg['status'] = 1
31             back_msg['msg'] = 'create success'
32         return Response(back_msg)
33 
34 
35 class Book(APIView, List, Create):
36     ret = models.Book
37     book_ser = BookSer
38 
39     def get(self, request):
40         return self.list()
41 
42     def post(self, request):
43         return self.create(request)
44 
45 
46 class BookDetail(APIView):
47     def get(self, request, pk):
48         ret = models.Book.objects.filter(pk=pk).first()
49         ser = BookSer(instance=ret, many=False)
50         return Response(ser.data)
51 
52     def put(self, request, pk):
53         ret = models.Book.objects.filter(pk=pk).first()
54         ser = BookSer(instance=ret, data=request.data)
55         if ser.is_valid():
56             ser.save()
57             return Response(ser.data)
58 
59     def delete(self, request, pk):
60         models.Book.objects.filter(pk=pk).delete()
61         return HttpResponse('already deleted')

 

mixin类和generice类编写视图

 1 from rest_framework.mixins import CreateModelMixin,RetrieveModelMixin,ListModelMixin,UpdateModelMixin,DestroyModelMixin
 2 from rest_framework.generics import GenericAPIView
 3 class PublishView(ListModelMixin,CreateModelMixin,GenericAPIView):
 4     queryset=models.Publish.objects.all()
 5     serializer_class=PublishSerializers
 6 
 7     def get(self, request):
 8         return self.list(request)
 9 
10     def post(self, request):
11         return self.create(request)
12 
13 class PublishDetailView(RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin,GenericAPIView):
14     queryset=models.Publish.objects.all()
15     serializer_class=PublishSerializers
16     def get(self,request,*args,**kwargs):
17         return self.retrieve(request,*args,**kwargs)
18     def put(self,request,*args,**kwargs):
19         return self.update(request,*args,**kwargs)
20     def delete(self,request,*args,**kwargs):
21         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

 

posted @ 2018-10-15 21:29  Roc_Atlantis  阅读(185)  评论(0编辑  收藏  举报