[Django]-How to ensure at least one of the Fields is not blank in Serializer?

7👍

You can use object-level validation:

for specific fields:

class NotificationsSerializer(serializers.Serializer):
    notify_add_friend = serializers.BooleanField(required=False)
    notify_added_to_group = serializers.BooleanField(required=False)

    def validate(self, data):
        if 'notify_add_friend' not in data and 'notify_added_to_group' not in data:
            raise serializers.ValidationError("Must include either notify_add_friend or notify_added_to_group")
        return data

for whole serializer:

class NotificationsSerializer(serializers.Serializer):
    notify_add_friend = serializers.BooleanField(required=False)
    notify_added_to_group = serializers.BooleanField(required=False)

    def validate(self, data):
        if not data:
            raise serializers.ValidationError("Must include at least one field")
        return data

Leave a comment