Get startedGet started for free

Schema validation with pydantic

It's your turn now! Use pydantic to enforce a schema in your MongoDB operations, defining a Movie class that you use to create a new movie you're about to insert. If you made a typo when creating the new movie, pydantic should complain!

This exercise is part of the course

Introduction to MongoDB in Python

View Course

Exercise instructions

  • Do the appropriate imports: from pydantic import BaseModel, and from typing import Optional.
  • Complete the definition of the Movie class so that genre is a list of strings and .
  • Finish the definition of new_movie. It was released in 2012 and has a rating of 8.0.
  • Insert the movie into the movies collection (available as mov).

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Do the appropriate imports
from ____ import BaseModel
from typing import ____

# Complete definition of Movie class
class Movie(____):
    title: str
    genre: ____[____]
    release_year: int
    ____: float
    won_oscar: ____[bool] = None

# Finish the details
new_movie = ____(
    title = "the avengers",
    genre = ["action", "adventure", "sci-fi"],
    ____ = ____,
    rating = ____
)

# Insert the movie into the movies collection (mov)
mov.____
Edit and Run Code