Last summer I designed and created a web-based application for a local non-profit that offers affordable swim lessons to children with disabilities. The application is designed to help streamline the pairing process between swimmers and instructors by allowing admins to upload a list of swimmers and instructors, automating the process of searching, filtering, and pairing based on various attributes such as gender, language, and swimming level.
def create_swimmer(data):
"""
Create a new swimmer entry in the database.
Ensures the swimmer doesn't already exist and adds the swimmer's details along with any related parents and lessons.
Args:
data (dict): The data for the new swimmer, including name, age, language, and any related parent or lesson IDs.
Returns:
dict: A dictionary representing the newly created swimmer.
"""
# Check if a swimmer with the same name already exists to avoid duplicates
existing_swimmer = Swimmer.query.filter_by(name=data.get('name')).first()
if existing_swimmer:
raise ValueError(f"Swimmer with the name {data.get('name')} already exists.")
# Create a new Swimmer object using the data provided
new_swimmer = Swimmer(
name=data.get('name'),
gender=data.get('gender'),
age=data.get('age'),
language=data.get('language'),
instructor_preference=data.get('instructor_preference'),
previous_instructor=data.get('previous_instructor'),
availabilities=data.get('availabilities'),
level=data.get('level'),
special_needs=data.get('special_needs'),
special_needs_info=data.get('special_needs_info'),
swim_experience=data.get('swim_experience'),
experience_details=data.get('experience_details'),
previous_swam_lessons=data.get('previous_swam_lessons'),
new_instructor_explanation=data.get('new_instructor_explanation'),
)
# Add the new swimmer to the session for committing to the database
db.session.add(new_swimmer)
db.session.commit()
# Associate any provided parent IDs with the swimmer
parent_ids = data.get('parent_ids', [])
for parent_id in parent_ids:
parent = db.session.get(Parent, parent_id)
if parent:
parent_swimmer = ParentSwimmer(parent_id=parent.id, swimmer_id=new_swimmer.id)
db.session.add(parent_swimmer)
# Associate any provided lesson IDs with the swimmer
lesson_ids = data.get('lesson_ids', [])
for lesson_id in lesson_ids:
lesson = db.session.get(Lesson, lesson_id)
if lesson:
new_swimmer.lessons.append(SwimmerLesson(lesson=lesson))
# Commit the associations (parents and lessons) to the database
db.session.commit()
# Return the newly created swimmer as a dictionary
return new_swimmer.to_dict()