正常来说遵循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都行