Bird
0
0

Consider this serializer snippet:

medium📝 component behavior Q4 of 15
Django - DRF Advanced Features
Consider this serializer snippet:
class UserSerializer(serializers.Serializer):
    age = serializers.IntegerField()

    def validate_age(self, value):
        if value < 21:
            raise serializers.ValidationError('Age must be at least 21')
        return value

What happens if {'age': 20} is validated?
AThe age 20 is accepted and returned without error
BA ValidationError is raised with message 'Age must be at least 21'
CThe serializer ignores the validate_age method and accepts the value
DThe serializer raises a TypeError due to missing return statement
Step-by-Step Solution
Solution:
  1. Step 1: Understand validate_age method

    The method checks if the age is less than 21 and raises ValidationError if true.
  2. Step 2: Apply validation to input 20

    Since 20 < 21, the condition triggers and raises the ValidationError with the specified message.
  3. Final Answer:

    A ValidationError is raised with message 'Age must be at least 21' -> Option B
  4. Quick Check:

    ValidationError raised for age < 21 [OK]
Quick Trick: validate_ raises error if condition fails [OK]
Common Mistakes:
MISTAKES
  • Forgetting to return the value after validation
  • Assuming validate_ is optional for field validation
  • Misunderstanding that ValidationError stops validation

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Django Quizzes