Django REST framework (三)类视图方式使用

  • A+
所属分类:Django REST framework

原创:www.pythonfans.cn

安装搭建环境:

安装以及项目搭建参考:Django REST framework (一)安装以及django项目创建

类视图使用:

1.新增view函数视图 :vim ly_ops/Idc/views.py

from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status

from django.http import Http404
from .models import Idc
from .serializers import IdcSerializer

class idc2(APIView):
    """
    获取Idc所有的对象,以及新增一个Idc对象
    """
    def get(self,request,format=None):#不能加*args,**kwargs
        query = Idc.objects.all()
        serializer = IdcSerializer(query,many=True)
        return Response(serializer.data)
    def post(self,request,format=None):
        serializer = IdcSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.data)

class idc_detail2(APIView):
    """
    对单个Idc对象的删改查
    """
    def get_idc_obj(self,pk):
        try:
            return Idc.objects.get(pk=pk)
        except ModuleNotFoundError:
            return Http404
    def get(self,request,pk,*args,**kwargs):
        idc_obj = self.get_idc_obj(pk)
        serializer = IdcSerializer(idc_obj)
        return Response(serializer.data)
    def put(self,request,pk,*args,**kwargs):
        idc_obj = self.get_idc_obj(pk)
        serializer = IdcSerializer(idc_obj,data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.data,
                        status=status.HTTP_400_BAD_REQUEST)
    def delete(self,request,pk,*args,**kwargs):
        idc_obj = self.get_idc_obj(pk)
        idc_obj.delete()
        return HttpResponse(status=status.HTTP_204_NO_CONTENT)

2.修改URL:vim ly_ops/ ly_ops/urls.py

urlpatterns = [
    path('idc2/',idc2.as_view()),
    re_path('idc2/(\d+)/',idc_detail2.as_view())
]

启动django,进行测试

python manage.py runserver 8000

新增一条数据:post 127.0.0.1:8000/idc2/

查看所有的数据:get 127.0.0.1:8000/idc2/

查看单条数据: get 127.0.0.1:8000/idc2/1/ #1代表id是1的数据

修改单条数据: put 127.0.0.1:8000/idc2/1/ #1代表id是1的数据

删除一条数据: delete 127.0.0.1:8000/idc2/1/ #1代表id是1的数据

Django REST framework (三)类视图方式使用
  • 我的微信
  • 这是我的微信扫一扫
  • weinxin
  • 我的微信公众号
  • 我的微信公众号扫一扫
  • weinxin

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: