Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Django REST Framework Security and Customization Validate Two Fields

validate 2 fields

im stuck

scorekeeper/serializers.py
from rest_framework import serializers

from . import models


class GameSerializer(serializers.ModelSerializer):
    class Meta:
        fields = ('id', 'name')
        model = models.Game


class PlayerSerializer(serializers.ModelSerializer):
    class Meta:
        fields = ('id', 'name', 'age', 'parent_approval')
        model = models.Player

    def validate_age(self, value):
        if value >= 13:
            return value
        raise serializers.ValidationError(
            'Player age must be over 13')


class ScoreSerializer(serializers.ModelSerializer):
    game = serializers.HyperlinkedRelatedField(
        read_only=True, view_name='apiv2:game-detail')
    player = serializers.HyperlinkedRelatedField(
        read_only=True, view_name='apiv2:player-detail')

    class Meta:
        fields = ('id', 'game', 'player', 'score')
        model = models.Score

1 Answer

diogorferreira
diogorferreira
19,363 Points

Hey Savious, I'd recommend reading the docs and going to the section labeled Object Level Validation, it allows you to validate multiple fields, which is needed for this challenge.

  • First, you'd create a validate method, that takes self and data (data being all the values passed in)
  • Then check whether the player is less than 13 and has parent_approval
  • If they don't then raise a serializers.ValidationError() with "Children under 13 require parental approval"
  • Otherwise, just return the data passed into the validation method

Hopefully you can solve it with that, if you need any more help then the code below is an example of what it could look like.

class PlayerSerializer(serializers.ModelSerializer):
    class Meta:
        fields = ('id', 'name', 'age', 'parent_approval')
        model = models.Player

    def validate(self, data):
        if data['age'] < 13 and not data['parent_approval']:
            raise serializers.ValidationError('Children under 13 require parental approval')
        return data

Hope it helps!