嗨大家好,我是Sean!
由於DRF的功能真的是很多且實用,我們再追加一篇獻給DRF的萬能(也幫前面漏講的東西補齊...)
我們先前有講到serializer,我們來補充serializer的關於驗證的部分。
除了原本的modelserializer以外,其實我們也可以field的方式表示:
from rest_framework import serializers
class PeopleSerializer(serializers.Serializer)
id = serializers.IntegerField(read_only=True)
name = serializers.CharField(max_length=20, unique=True)
age = serializers.IntegerField()
power = serializers.BooleanField()
bio = serializers.CharField(max_length=200)
除了本身的欄位類型會做認證以外,還有欄位裡的參數也會一併做驗證。另外,我們也可以自己寫功能來定義驗證:
from rest_framework import serializers
class PeopleSerializer(serializers.Serializer)
id = serializers.IntegerField(read_only=True)
name = serializers.CharField(max_length=20, unique=True)
age = serializers.IntegerField()
power = serializers.BooleanField()
bio = serializers.CharField(max_length=200)
# 新增驗證
def validate_age(self):
if self.age < 0:
raise serializers.ValidationError("Age must be bigger than 0!")
回到view的功能,若serializer.is_valid的地方,因為以上的validate_age出錯的話,便可以顯示我們寫好的ValidatorError的訊息!
接下來讓我們運用,新寫好的serializer,重新寫一次view試試。
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .models import People
from .serializers import PeopleSerializer
@api_view(['GET', 'POST'])
def people_list(request):
if request.method == 'GET':
people = People.objects.all()
serializer = PeopleSerializer(people, many=True)
return Response(serializer.data)
elif request.method == 'POST':
serializer = PeopleSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
完成url後,我們就一樣來啟動專案
那麼今天的文章,就先到此結束!
我是Sean,你各位海上的人,我們明天見!