Django DRF 相关命令

#导入DRF的视图类、response

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

#跳转路由

views.定义的视图类.as_view()

#在views下创建视图类

class 类名(APIView):

使用序列化组件Serializer序列化数据库中数据(需要序列化的字段必须与数据库中的一致)

新建serializer.py
#from rest_freamework.serializers import Serializer
from rest_freamework import serializers
class 自定义序列化类(serializers.Serializer):
  name=serializers.xxx
  …

视图下调用序列化类

序列化类(instance=查询数据, many=True) #many字段用于查询多条数据

使用序列化组件ModelSerializer序列化数据库中数据

from rest_freamework import serializers
from x.models import y(表)                            #导入需要序列化的模型
class 自定义序列化类(serializers.ModelSerializer):
  class Meta:
    model=xxx         #设置需要序列化的模型
    fields='__all__'  #对所有字段进行序列化

反序列化新增数据

def post(self, request):
    ser = bookmodser(data=request.data)
    if ser.is_valid():
        ser.save()
        return Response(ser.data,status=200)

修改数据

def put(self, request, num):
    book_obj = books.objects.filter(id=num).first()
    ser = bookmodser(instance=book_obj, data=request.data)
    if ser.is_valid():
        ser.save()
        return Response(ser.data, status=201)
    else:
        return Response(ser.errors, status=400)

删除数据

def delete(self, request, num):
    res = books.objects.filter(id=num).delete()
    if res:
        return Response("删除成功", status=404)

GenericAPIView视图类的使用( 单条和多条需配合两个类来实现。)


有两个类属性
    queryset = Book.objects.all()  # 你要序列化的数据
    serializer_class = serializer.BookSerializer # 你要使用的序列化类
三个方法
    get_queryset() # 获取要序列化的数据
    get_serializer() # 获取要使用的序列化类
    get_object()    # 获取单条数据(一定要用pk,如果你想改,重写类属性lookup_field)

'''
from rest_framework.generics import GenericAPIView

class BookView(GenericAPIView):
    queryset = Book.objects.all()  # 你要序列化的数据
    serializer_class = serializer.BookSerializer  # 你要使用的序列化类

    def get(self, request):
        qs = self.get_queryset()  # GenericAPIView提供的等同于self.queryset
        ser = self.get_serializer(instance=qs, many=True)  # GenericAPIView提供的等同于self.serializer_class
        return Response(data=ser.data, status=200)

    def post(self, request):
        ser = self.get_serializer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response(data={'code': 100, 'msg': '创建成功'})
        else:
            return Response(data=ser.errors)

class BookDetailView(GenericAPIView):
    queryset = Book.objects.all()  # 你要序列化的数据
    serializer_class = serializer.BookSerializer  # 你要使用的序列化类

    def get(self, request, *args, **kwargs):
        book = self.get_object()  # 获取单条
        ser = self.get_serializer(instance=book)
        return Response(data=ser.data, status=200)

    def put(self, request, pk):
        book = self.get_object()
        ser = self.get_serializer(data=request.data, instance=book)
        if ser.is_valid():
            ser.save()
            return Response(data={'code': 100, 'msg': '修改成功'})
        else:
            return Response(data=ser.errors)

    def delete(self, request, pk):

        self.get_object().delete()

        return Response(data={'code': 100, 'msg': '删除成功'})

继承GenericAPIView+5个视图扩展类

不是视图类,没有继承APIView及其子类
from rest_framework.mixins import ListModelMixin,CreateModelMixin,RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin

from rest_framework.generics import GenericAPIView

class BookView(GenericAPIView,ListModelMixin,CreateModelMixin):
    queryset = Book.objects.all()  # 要序列化的数据
    serializer_class = serializer.BookSerializer  # 要使用的序列化类

    def get(self, request):
        return self.list(request)

    def post(self, request):
        return self.create(request)

class BookDetailView(GenericAPIView,RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin):
    queryset = Book.objects.all()  # 要序列化的数据
    serializer_class = serializer.BookSerializer  # 要使用的序列化类

    def get(self, request, *args, **kwargs):
        return self.retrieve(request, *args, **kwargs)

    def put(self, request, *args, **kwargs):
        return self.update(request, *args, **kwargs)

    def delete(self, request, *args, **kwargs):
        return self.destroy(request, *args, **kwargs)

继承GenericAPIView+9个视图扩展类

9个视图子类
from rest_framework.generics import ListAPIView, CreateAPIView, ListCreateAPIView
from rest_framework.generics import RetrieveAPIView, UpdateAPIView, DestroyAPIView, RetrieveUpdateAPIView, RetrieveDestroyAPIView, RetrieveUpdateDestroyAPIView

# ListAPIView:GenericAPIView+ListModelMixin

class BookView(ListCreateAPIView):
    queryset = Book.objects.all()  # 要序列化的数据
    serializer_class = serializer.BookSerializer  # 要使用的序列化类

class BookDetailView(RetrieveUpdateDestroyAPIView):
    queryset = Book.objects.all()  # 要序列化的数据
    serializer_class = serializer.BookSerializer  # 要使用的序列化类
版权声明:本文采用知识共享 署名4.0国际许可协议 [BY-NC-SA] 进行授权
文章名称:《Django DRF 相关命令》
文章链接:https://wrlog.cn/2022/04/1179/
本站资源仅供个人学习交流,请于下载后24小时内删除,不允许用于商业用途,否则法律问题自行承担。