Bird
0
0

Identify the error in this serializer validation code:

medium📝 Debug Q14 of 15
Django - DRF Advanced Features
Identify the error in this serializer validation code:
class ProductSerializer(serializers.Serializer):
    price = serializers.FloatField()

    def validate(self, data):
        if data['price'] < 0:
            raise serializers.ValidationError('Price must be positive')
        return data

    def validate_price(self, value):
        if value == 0:
            raise serializers.ValidationError('Price cannot be zero')
        return value
Avalidate method should call super().validate(data)
Bvalidate_price should return data, not value
CNo error, code is correct
DValidationError messages must be dictionaries, not strings
Step-by-Step Solution
Solution:
  1. Step 1: Check validate_price method

    It correctly checks if value is zero and raises error, then returns value.
  2. Step 2: Check validate method

    It checks if price is negative and raises error, then returns data dictionary.
  3. Step 3: Confirm ValidationError usage

    Passing string message is allowed; dictionary is optional for field-specific errors.
  4. Final Answer:

    No error, code is correct -> Option C
  5. Quick Check:

    Both validate and validate_ methods are valid [OK]
Quick Trick: Both validate and validate_ can coexist and return correct types [OK]
Common Mistakes:
MISTAKES
  • Expecting validate_price to return data dict
  • Thinking super().validate(data) is mandatory
  • Believing ValidationError must be dict only

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Django Quizzes