drf序列化用APIView寫編寫5個介面並校驗資料

-半城烟雨發表於2024-04-17
  • 步驟:
    • 寫一個類,繼承Serialier
    • 在類中寫欄位,欄位就是要序列化的欄位
    • 在檢視函式中,序列化類,例項化得到物件,傳入該傳的引數
    • 呼叫序列化類物件的 serializer.data 方法完成序列化

【一】寫序列化類

  • serializer.py
from rest_framework import serializers
from rest_framework.exceptions import ValidationError


class BookSerializer(serializers.Serializer):
    name = serializers.CharField(max_length=8, min_length=3)
    price = serializers.IntegerField(max_value=100, min_value=10)

    # 區域性鉤子
    def validate_name(self, name):
        if name.startswith('sb'):
            raise ValidationError('書名不能以sb開頭')
        else:
            return name

    # 全域性鉤子
    def validate(self, attrs):
        # attrs是字典
        name = attrs.get('name')
        price = attrs.get('price')
        if name.startswith('sb') and price > 50:
            raise ValidationError('書名不能以sb開頭,價格不能超過50')
        else:
            return attrs


【二】後端

from .serializer import BookSerializer
from rest_framework.response import Response
class BookView(APIView):
    def get(self, request):
        obj_list = Book.objects.all()
        # 多條資料many=True
        serializer = BookSerializer(instance=obj_list,many=True)
        return Response({'code': 100, 'msg': "查詢成功", 'results': serializer.data})
    # 增加
    def post(self, request):
        # 校驗資料
        serializer=BookSerializer(data=request.data)
        if serializer.is_valid():
            # Book.objects.create(name=request.data.get('name'), price=request.data.get('price'))
            return Response({'code': 100, 'msg': "儲存成功"})
        else:
            return Response({'code': 101, 'msg':"儲存失敗", 'results': serializer.errors})


class BookDetailView(APIView):
    def get(self, request, pk):
        obj = Book.objects.filter(pk=pk).first()
        serializer = BookSerializer(instance=obj)
        return Response({'code': 100, 'msg': "查詢成功", 'results':serializer.data})

    # 修改
    def put(self, request, pk):
        Book.objects.filter(pk=pk).update(name=request.data.get('name'), price=request.data.get('price'))
        return JsonResponse({'code': 100, 'msg': "修改成功"})

    def delete(self, request, pk):
        obj = Book.objects.filter(pk=int(pk)).delete()
        return JsonResponse({'code': 100, 'msg': "刪除成功"})

【三】測試

image-20240411194115343

【四】校驗

image-20240411200936024

相關文章