Challenge 3: Validate Incoming Data — Possible Solution ==================================================================== # catalog/serializers.py from rest_framework import serializers from .models import Book class BookSerializer(serializers.ModelSerializer): price = serializers.DecimalField(max_digits=6, decimal_places=2, min_value=0) class Meta: model = Book fields = ["id", "title", "price", "in_stock"] # --- Demonstrating validation with a negative price --- >>> from catalog.serializers import BookSerializer >>> serializer = BookSerializer(data={ ... "title": "Discounted Book", ... "price": "-5.00", ... "in_stock": True, ... }) >>> serializer.is_valid() False >>> serializer.errors {'price': [ErrorDetail(string='Ensure this value is greater than or equal to 0.', code='min_value')]} # Compare to a valid submission: >>> valid_serializer = BookSerializer(data={ ... "title": "Regular Book", ... "price": "9.99", ... "in_stock": True, ... }) >>> valid_serializer.is_valid() True >>> valid_serializer.errors {} WHY THIS WORKS -------------- - min_value=0 on the DecimalField adds a validator that runs as part of is_valid() — a submitted price below zero fails validation before the serializer ever attempts to save anything, exactly like Course 1's clean_price() custom ModelForm validation achieved a very similar rule by hand. - serializer.is_valid() returns a plain boolean, and serializer.errors is only meaningfully populated AFTER is_valid() has been called (calling .errors before .is_valid() would either be empty or raise, depending on DRF version) — this mirrors the is_valid()/cleaned_data pattern from Django's own Forms in Course 1 almost exactly, since DRF's serializers were deliberately designed to feel familiar to anyone who already knows Django Forms. - The error message itself ("Ensure this value is greater than or equal to 0.") is DRF's built-in validator message for min_value — no custom clean_price()-style method was needed here, since DecimalField's own min_value argument covers this specific rule directly.