京西商城——基于viewset视图集开发评论接口

在使用GenericAPIView和Mixins开发时,确实可以大大提高编码的速度以及减少代码量,但是在一个视图里并不能实现5个基础的请求方法,要用两个视图类来完成。所以我们可以使用viewset(视图集)来将两个视图类合并

如果要使用viewset的话,要配置urls以将HTTP请求映射到ViewSet

comment/views.py
from rest_framework import viewsets
from apps.comment.models import Comment
from apps.comment.serializers import CommentSerializer


class CommentViewSet(viewsets.ModelViewSet):
    queryset = Comment.objects
    serializer_class = CommentSerializer

    def get_queryset(self):
        # 确保返回标准的Django QuerySet
        return Comment.objects.all()
comment/urls.py
from django.urls import path
from apps.comment.views import CommentViewSet

urlpatterns = [
    path('', CommentViewSet.as_view({
        'get': 'list',
        'post': 'create'
    })),
    path('<int:pk>/', CommentViewSet.as_view({
        'get': 'retrieve',
        'post': 'update',
        'delete': 'destroy'
    }))
]

在这里插入图片描述

可以看到在基于ViewSet开发的CommentViewSet接口时不需要为每种HTTP请求方法编写对应的处理方法

ModelViewSet 同时包含了ListModelMixinCreateModelMixinRetrieveModelMixinUpdateModelMixinDestroyModelMixin,包含了所有的CURD。

如果你只需要获取和创建操作,你可以使用ReadOnlyModelViewSet,它只包含ListModelMixinRetrieveModelMixin


在viewset类中,ViewSetMixin是所有类的基类,正是因为在它之中重写了as_view方法,这是将ViewSet转换为可调用视图的关键步骤。

并定义了action参数,通过actions关键字参数,你可以指定哪些HTTP方法应该映射到ViewSet中的哪些动作。

这是源码对ViewSetMixin这个类的解释:

"""
    This is the magic.

    Overrides `.as_view()` so that it takes an `actions` keyword that performs
    the binding of HTTP methods to actions on the Resource.

    For example, to create a concrete view binding the 'GET' and 'POST' methods
    to the 'list' and 'create' actions...

    view = MyViewSet.as_view({'get': 'list', 'post': 'create'})
    """

基于generics开发时不过也就是把GenericAPIView与ListModelMixinCreateModelMixinRetrieveModelMixinUpdateModelMixinDestroyModelMixin相互组合,只不过在使用时就没有想viewset那样高抽象了,基于generics开发时就需要自己编写各个请求对应的方法了。

在这里插入图片描述

若有错误与不足请指出,关注DPT一起进步吧!!!

  • 20
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

叫我DPT

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值