In Example 10-2, what is the purpose of the row_to_model and model_to_dict functions, and how do they relate to the sqlite3 cursor methods?
row_to_model converts a row tuple returned by a sqlite3 cursor fetch method into a Pydantic Creature model. model_to_dict converts a Pydantic model into a dictionary so its values can be passed as named parameters to cursor.execute(). They translate between database rows/parameters and application model objects.
In Example 10-2, sqlite3 cursor methods like execute() and fetchone() work with Python tuples and dictionaries. A SELECT query, when fetched, returns each row as a tuple, so row_to_model() unpacks that tuple into named fields and constructs a Creature object. This lets higher layers work with model objects instead of raw tuples. Conversely, model_to_dict() takes a Creature model and returns creature.dict(), a dictionary whose keys are field names. That dictionary is then passed as the params argument to curs.execute() with named-style placeholders such as :name or :country. Thus these helpers adapt the sqlite3 DB-API data shapes into the application's Pydantic model format, and back again for query parameters.
Key points
- row_to_model() converts a tuple returned by cursor fetch functions into a Creature model.
- model_to_dict() turns a Pydantic model into a dictionary suitable for named query parameters.
- sqlite3 fetch methods return tuples for SELECT rows; cursor.execute accepts parameter dictionaries.
- These functions bridge the DB-API layer and the model layer without mixing data formats.
Related questions
FastAPI: Modern Python Web Development
Bill Lubanovic;
First Edition · O'Reilly Media, Inc.