1. 程式人生 > >一版圖書_英雄專案的序列化器檔案

一版圖書_英雄專案的序列化器檔案

from rest_framework import serializers
from .models import BookInfo, HeroInfo


class BookSerializer(serializers.Serializer):
    id = serializers.IntegerField(read_only=True)
    btitle = serializers.CharField()
    bpub_date = serializers.DateField()
    bread = serializers.IntegerField(
        required=False,
        min_value=10,
        max_value=20,
        error_messages={
            'min_value': '最小值為10'
        }
    )
    bcomment = serializers.IntegerField(required=False)

    def validate_btitle(self, value):
        # 定義程式碼 進行驗證
        if '天' not in value:
            # 當驗證不滿足條件時
            raise serializers.ValidationError('content 天')
        return value

    def validate(self, attrs):
        bread = attrs.get('bread')
        bcomment = attrs.get('bcomment')
        if bread < bcomment:
            raise serializers.ValidationError('閱讀量必須大於評論量')
        return attrs

    def create(self, validate_data):
        book = BookInfo.objects.create(**validate_data)
        return book

    def update(self, instance, validated_data):
        instance.btitle = validated_data.get('btitle')
        instance.bpub_date = validated_data.get('bpub_date')

        if validated_data.get('bread'):
            instance.bread = validated_data.get('bread')
        if validated_data.get('bcomment'):
            instance.bcomment = validated_data.get('bcomment')
        instance.save()
        return instance


class HeroSerializer(serializers.ModelSerializer):
    hbook_id = serializers.IntegerField()
    hbook = serializers.StringRelatedField(read_only=True)

    class Meta:
        model = HeroInfo  # 注意大小寫和model拼寫
        fields = '__all__'