rest_framework - 视图

准备models表结构

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

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

class User(models.Model):
    user = models.CharField(max_length=32)
    pwd = models.CharField(max_length=32)
    user_type = models.IntegerField(choices=((1, "普通用户"), (2, "VIP"), (3, "sVIP")), default=1)

class UserToken(models.Model):
    user = models.OneToOneField(to="user")
    token = models.CharField(max_length=128)
View Code

APIView的查询所有、添加

        ---url.py

url(r"books/(\d+)/$",views.BookView.as_view()),

        视图部分

class BookView(APIView):
    def get(self,request,*args,**kwargs):
        book_list = Book.objects.all()
        # 一定要加“context={'request': request}”,不然会报错
        bs = BookSerializers(book_list,many=True,context={'request': request})
        return Response(bs.data)

    def post(self,request,*args,**kwargs):
        # 一定要加“context={'request': request}”,不然会报错
        bs = BookSerializers(data=request.data,context={'request': request})
        if bs.is_valid():
            bs.save()
            return Response(bs.data)
        else:
            return Response(bs.errors)

查询单个数据、修改、删除

        ---url.py

url(r"bookdetail/$",views.BookViewDetail.as_view()),

        视图部分

class BookViewDetail(APIView):
        #查看一本书
    def get(self, request, pk, *args, **kwargs):
        obj=Book.objects.filter(pk=pk).first()
        if obj:
            bs=BookSerializers(obj,context={'request': request})
            return Response(bs.data)
        else:
            return Response()

        # 删除一本书
    def delete(self,request,pk,*args,**kwargs):
        Book.objects.filter(pk=pk).delete()
        return Response()

        # 编辑一本书
    def put(self,request,pk,*args,**kwargs):
        # obj :编辑书籍对象
        obj = Book.objects.filter(pk=pk).first()
        bs = BookSerializers(data=request.data,instance=obj,context={'request': request})
        if bs.is_valid():
            bs.save()
            return Response(bs.data)
        else:
            return Response(bs.errors)

   查看单个数据:

        http://127.0.0.1:8000/bookdetail/1/ (get方式)

        修改单个数据:

        http://127.0.0.1:8000/bookdetail/1/ (put方式) + json数据

        删除单个数据

        http://127.0.0.1:8000/bookdetail/1/ (gdelete方式)

        省略测试图片...

基于Mixin编写视图

        url.py

url(r"books/$",views.BookView.as_view()),
url(r"bookdetail/(?P<pk>\d+)/$",views.BookViewDetail.as_view()),

        视图部分

# 序列化组件
from api.service.serializers import BookSerializers,PublishSerializers

#
mixins:对数据进行查询,增加、修改、删除的基本构建模块 from rest_framework import mixins # ListModelMixin,CreateModelMixin,UpdateModelMixin,DestroyModelMixin

# generics:通常 需要的行为 的通用视图。 from rest_framework import generics # Mixin+APIView:(ListModelMixin,GenericAPIView)

class BookViewSet(mixins.ListModelMixin, # 展示视图,基类为object mixins.CreateModelMixin, # 增加视图 generics.GenericAPIView # 基于APIView的通用视图 ): queryset = Book.objects.all() serializer_class = BookSerializers # 返回ListModelMixin类中的list方法 def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) # 返回CreateModelMixin类中的create方法 def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) class BookDetailView(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, generics.GenericAPIView ): queryset = Book.objects.all() serializer_class = BookSerializers 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.delete(request, *args, **kwargs) class PublishViewSet(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView ): queryset = Publish.objects.all() serializer_class = PublishSerializers 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 PublishDetailView(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, generics.GenericAPIView ): queryset = 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.delete(request, *args, **kwargs)

        优化以上代码:

        --- api.serializers.py

class BookSerializers(serializers.ModelSerializer):
    publish = serializers.HyperlinkedIdentityField(
        view_name="book_detail",    # 是urls.py中的name的值
        lookup_field="publish_id",  # 在页面展示时的格式
        lookup_url_kwarg="pk"       # url中的分组名
    )

    class Meta:
        model = Book
        fields = "__all__"


class PublishSerializers(serializers.ModelSerializer):
    class Meta:
        model = Publish
        fields = "__all__"

        视图部分

# 封装了大多数 需要行为的 通用视图:源码中有介绍
from
rest_framework improt generics class BookView(generics.ListCreateAPIView): queryset = Book.objects.all() serializer_class = BookSerializers class BookDetailView(generics.RetrieveUpdateDestroyAPIView): queryset = Book.objects.all() serializer_class = BookSerializers class PublishView(generics.ListCreateAPIView): queryset = Publish.objects.all() serializer_class = PublishSerializers class PublishDetailView(generics.RetrieveUpdateDestroyAPIView): queryset = Publish.objects.all() serializer_class = PublishSerializers

viewsrts.Model.ModelViewSet

        --- url.py

from django.conf.urls import url
from django.contrib import admin
from api import views
# from rest_framework import genericAPIView.as_view
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^books/$', views.BookView.as_view({"get": "list", "post": "create"})), # as_view中的参数(字典),执行的是genericAPIView.as_view中的initkwargs(同级继承/查找,非父类继承)
    url(r'^publishes/$', views.PublishView.as_view({"get": "list", "post": "create"})),
    url(r'^books/(?P<pk>\d+)/$', views.BookDetailView.as_view({'get': 'retrieve','put': 'update','patch': 'partial_update','delete': 'destroy'}), name="book_detail"),
    url(r'^publishes/(?P<pk>\d+)/$', views.PublishDetailView.as_view({'get': 'retrieve','put': 'update','patch': 'partial_update','delete': 'destroy'}), name="book_detail"),
]

        视图部分

# 这一部分被移到了 api.service.serializers文件中了(序列化组件)
from rest_framework import serializers
from ..models import *

# --- Book表的序列化组件start --- #
class BookSerializers(serializers.ModelSerializer):
    publish = serializers.HyperlinkedIdentityField(
        view_name="book_detail",  # 是urls.py中的name的值
        lookup_field="publish_id",  # 在页面展示时的格式
        lookup_url_kwarg="pk"
    )

    class Meta:
        model = Book
        fields = "__all__"

# Publish表的序列化组件
class PublishSerializers(serializers.ModelSerializer):
    class Meta:
        model = Publish
        fields = "__all__"
# --- Book表的序列化组件stop --- #

    --- 视图部分
from rest_framework import viewsets
# 重写as_view方法,它执行一个"actions"关键字HTTP方法与资源上的操作的绑定。

class BookView(viewsets.ModelViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializers


class BookDetailView(viewsets.ModelViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializers


class PublishView(viewsets.ModelViewSet):
    queryset = Publish.objects.all()
    serializer_class = PublishSerializers


class PublishDetailView(viewsets.ModelViewSet):
    queryset = Publish.objects.all()
    serializer_class = PublishSerializers 

 

posted @ 2018-04-12 21:57  焦国峰的随笔日记  阅读(87)  评论(0编辑  收藏  举报
// ############################### // ##############################