django restful使用,rest framework设计典范,基于viewset以及mixins的方式

上节收到使用APIView的方式实现的rest接口,但是有的小伙问道为什么使用viewset来写接口,所有下面就来介绍使用viewset的方式。
前提:已经有了一个可以正常运行的django rest framework的project
1、定义模型

from django.db import models

class Product(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    name = models.CharField(max_length=100,default='')
    describe = models.CharField(max_length=500,default='')
    price = models.FloatField()
    isDelete = models.BooleanField(default=False)
    class Meta:
        db_table = 'product_table'

2、定义你的serializers.py

from rest_framework import serializers
from denweiCompany.models import Product,SimulateLogin

class ProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = ('id','created','name','describe','price','isDelete')

3、定义你的基于viewset的views.py

from yourapp.models import Product
from yourapp.serializers import ProductSerializer
from rest_framework import mixins
from rest_framework import generics
from rest_framework.pagination import PageNumberPagination
class GoodsListPagination(PageNumberPagination):
    # 单页数据量
    page_size = 5
    page_size_query_param = 'page_size'
    page_query_param = 'p'
    # 单页最大数据量
    max_page_size = 10

class GoodsListViewSet(mixins.ListModelMixin,mixins.CreateModelMixin,mixins.RetrieveModelMixin,mixins.DestroyModelMixin,mixins.UpdateModelMixin,viewsets.GenericViewSet):
    #指定querset
    queryset = Product.objects.all()
    # 注册使用的序列化类
    serializer_class = ProductSerializer
    # 注册使用的分页类
    pagination_class = GoodsListPagination

4、使用router来配置你的自动化路由

from django.conf.urls import url, include
# 使用router自动处理url和view
from rest_framework.routers import DefaultRouter
from yourapp.views import GoodsListViewSet
router = DefaultRouter()
router.register(r'productviewset',GoodsListViewSet)

urlpatterns = [
    # 使用router 自动处理
    url(r'^',include(router.urls)),
]

这样设置的话,你对http://127.0.0.1:8000/yourapp/productviewset接口就可以轻松的完成增删改查等操作。
这里在介绍一下继承mixin的类是用来干嘛用的:
mixins.ListModelMixin 定义list方法,返回一个queryset列表 GET
mixins.CreateModelMixin 定义create方法,创建一个实例 POST
mixins.RetrieveModelMixin 定义Retrieve方法,返回一个具体事例 GET
mixins.UpdateModelMixin 定义update方法,对某个实例进行更行 UPDATE
mixins.DestoryModelMixin 定义delete方法,删除某个实例 Delete
因此你要获取列表数据时直接对接口http://127.0.0.1:8000/yourapp/productviewse发起一个GET请求即可
GET请求 http://127.0.0.1:8000/yourapp/productviewse/3/ 就是获取id为3的具体数据
DELETE请求 http://127.0.0.1:8000/yourapp/productviewse/3/ 就是删除id为3的数据
PUT PATCH等方法类似
……..

猜你喜欢

转载自blog.csdn.net/haeasringnar/article/details/80868190
今日推荐