Bird
0
0

Given this serializer code, what will happen if age is less than 18?

medium📝 component behavior Q13 of 15
Django - DRF Advanced Features
Given this serializer code, what will happen if age is less than 18?
class UserSerializer(serializers.Serializer):
    age = serializers.IntegerField()

    def validate_age(self, value):
        if value < 18:
            raise serializers.ValidationError('Must be at least 18')
        return value
AValidationError with message 'Must be at least 18' is raised
BThe age is automatically set to 18
CNo error, age is accepted as is
DSerializer ignores the age field
Step-by-Step Solution
Solution:
  1. Step 1: Understand the validate_age method logic

    The method checks if age is less than 18 and raises ValidationError if true.
  2. Step 2: Predict behavior when age < 18

    If age is less than 18, the error is raised stopping validation and returning the message.
  3. Final Answer:

    ValidationError with message 'Must be at least 18' is raised -> Option A
  4. Quick Check:

    Age < 18 triggers ValidationError [OK]
Quick Trick: ValidationError raised when condition inside validate_ fails [OK]
Common Mistakes:
MISTAKES
  • Assuming age is changed automatically
  • Thinking no error occurs for invalid age
  • Believing the field is ignored silently

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Django Quizzes