DFR-类视图(ViewSet)
基础的ViewSet
views.py
from rest_framework import viewsets
from .models import Merchant
from .serializers import MerchantSerializer
from rest_framework.response import Response
from rest_framework import status
from django.shortcuts import get_object_or_404
class MerchantViewSet(viewsets.ViewSet):
def list(self,request):
# get请求
queryset = Merchant.objects.all()
serializer = MerchantSerializer(queryset,many=True)
return Response(data=serializer.data)
def create(self,request):
# post
serializer = MerchantSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response("success")
else:
return Response("fail",status=status.HTTP_400_BAD_REQUEST)
def retrieve(self,request,pk=None):
# 查询
queryset = Merchant.objects.all()
merchant = get_object_or_404(queryset,pk=pk)
serializer = MerchantSerializer(merchant)
return Response(serializer.data)
def update(self,request,pk=None):
# put
queryset = Merchant.objects.all()
merchant = get_object_or_404(queryset, pk=pk)
serializer = MerchantSerializer()
serializer.update(merchant,request.data)
return Response('success')
def destroy(self,request,pk=None):
# delete
queryset = Merchant.objects.all()
merchant = get_object_or_404(queryset,pk=pk)
merchant.delete()
return Response('success')
进阶版:ModelViewSet
上面的例子直接用下面的views.py
内容即可实现
views.py
class MerchantViewSet(viewsets.ModelViewSet):
queryset = Merchant.objects.all()
serializer_class = MerchantSerializer
高级版
在当前的视图集中增加其他的url,这时候可以使用@active
实现
views.py
from rest_framework.decorators import action
class MerchantViewSet(viewsets.ModelViewSet):
queryset = Merchant.objects.all()
serializer_class = MerchantSerializer
@action(['GET'],detail=False)
def cs(self,request,*args,**kwargs):
queryset = self.get_queryset()
queryset = queryset.filter(name__contains="长沙")
serializer = MerchantSerializer(queryset,many=True)
return Response(serializer.data)
urls.py
路由部分不需要修改。以后直接可以通过/merchant/cs/
可以访问到name中包含了"长沙"两个字的所有商家。
url的书写
使用视图集时,路由应按照下面的方式写。
urls.py
from rest_framework.routers import DefaultRouter
router = DefaultRouter(trailing_slash=False)
router.register('merchant/',views.MerchantView,basename='merchant')
urlpatterns = [] + router.urls