Django viewsets 视图集与 router 路由实现评论接口开发

正常来说遵循restful风格编写接口,定义一个类包含了 get post delete put 四种请求方式,这四种请求方式是不能重复的
例如:获取单条记录和多条记录使用的方式都是get,如果两个都要实现的话那么得定义两个类,因为在同一个类中不能有两个get
这里继承ViewSetMixin来解决该问题(根据是否传参)

comment/views

注意ViewSetMixin继承顺序要放在第一个

python 复制代码
from django.http import JsonResponse
from django.shortcuts import render
from rest_framework.generics import GenericAPIView
from rest_framework.mixins import ListModelMixin, CreateModelMixin, RetrieveModelMixin, UpdateModelMixin, \
    DestroyModelMixin
from rest_framework.viewsets import ViewSetMixin

from apps.comment.models import Comment
from apps.comment.serializers import CommentSerializer


# Create your views here.
class CommentGenericAPIView(ViewSetMixin,
                            GenericAPIView,
                            ListModelMixin,
                            CreateModelMixin,
                            RetrieveModelMixin,
                            UpdateModelMixin,
                            DestroyModelMixin
                            ):
    queryset = Comment.objects
    serializer_class = CommentSerializer

    def single(self,request,pk):
        print("我是查询一个")
        return self.retrieve(request,pk)

    def my_list(self,request):
        print("我是查询多个")
        return self.list(request)

    def edit(self,request,pk):
        print("我是更新")
        return self.update(request,pk)

    def my_save(self,request):
        print("我是保存")
        return self.create(request)

    def my_delete(self,request,pk):
        print("我是删除")
        return self.destroy(request,pk)

comment/urls

python 复制代码
from django.urls import path, re_path
from .views import CommentGenericAPIView

urlpatterns = [
    path("",CommentGenericAPIView.as_view({
        "get":"my_list",
        "post":"my_save"   #保存
    })),
    re_path("(?P<pk>.*)",CommentGenericAPIView.as_view(
        {
            "get":"single",
            "post":"edit",  #编辑
            "delete":"my_delete"
        }
    )),
]

comment/models

python 复制代码
from django.db import models

# Create your models here.
from django.db import models


class Comment(models.Model):
    user_id = models.IntegerField(blank=True, null=True)
    sku_id = models.CharField(max_length=255, blank=True, null=True)
    content = models.CharField(max_length=255, blank=True, null=True)
    user_image_url = models.CharField(max_length=255, blank=True, null=True)
    reference_name = models.CharField(max_length=255, blank=True, null=True)
    score = models.IntegerField(blank=True, null=True)
    nickname = models.CharField(max_length=255, blank=True, null=True)
    reply_count = models.CharField(max_length=255, blank=True, null=True)
    create_time = models.DateTimeField(blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'comment'

comment/serializers.py

python 复制代码
from rest_framework import serializers

from apps.comment.models import Comment
from apps.goods.models import Goods



class CommentSerializer(serializers.ModelSerializer):

    class Meta:
        model = Comment
        fields = "__all__"

viewsets 路由原理解析

ViewSetMixin中没有路由分发的方法,所以此处继承了GenericAPIView(View中有),不然不能进行路由的分发,继承APIView或者View都行

相关推荐
weixin_BYSJ198712 小时前
django在线图书销售平台---附源码16192
java·javascript·spring boot·python·django·flask·php
kobe_OKOK_14 小时前
django外键字段会自动在数据库字段后面加上_id
数据库·django·sqlite
梅雅达编程笔记1 天前
零基础学 Python 第14章 | 模块、包与第三方库
开发语言·python·django·numpy·pandas
梅雅达编程笔记1 天前
零基础学 Python 第15章 | 类与对象:面向对象编程入门
开发语言·python·django·numpy·pandas
2401_868534782 天前
OSPF经典案例分析
python·django
不瘦80斤不改名2 天前
全家桶、乐高积木与类型引擎:重新认识 Django、Flask 与 FastAPI
django·flask·fastapi
hanxiuchao7 天前
告别客户端臃肿!网页端 M3U8 播放调试方案,适配全办公场景
运维·python·django·m3u8·m3u8播放
程序员羽痕7 天前
基于深度学习的眼疾识别系统
人工智能·pytorch·深度学习·分类·django
流云鹤7 天前
1. 配置环境、创建导航栏
python·django
流云鹤7 天前
2.登录模块
python·django