### Install SQLModel with uv Source: https://github.com/fastapi/sqlmodel/blob/main/docs/virtual-environments.md If you have uv installed, use this command to install the SQLModel package. ```console $ uv pip install sqlmodel ---> 100% ``` -------------------------------- ### Example requirements.txt content Source: https://github.com/fastapi/sqlmodel/blob/main/docs/virtual-environments.md A sample requirements.txt file showing how to specify packages and their versions. ```requirements.txt sqlmodel==0.13.0 rich==13.7.1 ``` -------------------------------- ### Install packages from requirements.txt with uv Source: https://github.com/fastapi/sqlmodel/blob/main/docs/virtual-environments.md If you have uv installed, use this command to install packages from your requirements.txt file. ```console $ uv pip install -r requirements.txt ---> 100% ``` -------------------------------- ### Install FastAPI and Uvicorn Source: https://github.com/fastapi/sqlmodel/blob/main/docs/tutorial/fastapi/simple-hero-api.md Install FastAPI for building the web API and Uvicorn as the ASGI server. Ensure you are in an activated virtual environment. ```console $ pip install fastapi "uvicorn[standard]" ---> 100% ``` -------------------------------- ### Create Database and Tables on Startup Source: https://github.com/fastapi/sqlmodel/blob/main/docs/tutorial/fastapi/simple-hero-api.md Define a function to create the database and tables, and register it to be called once when the application starts. ```python from sqlmodel import SQLModel, create_engine def create_db_and_tables(): SQLModel.metadata.create_all(engine) @app.on_event("startup") def startup_event(): create_db_and_tables() ``` -------------------------------- ### Install SQLModel Source: https://github.com/fastapi/sqlmodel/blob/main/docs/index.md Install SQLModel using pip. Ensure you have a virtual environment activated. ```console $ pip install sqlmodel ---> 100% Successfully installed sqlmodel ``` -------------------------------- ### Example PATH before activation (Windows) Source: https://github.com/fastapi/sqlmodel/blob/main/docs/virtual-environments.md Illustrates a typical PATH environment variable on Windows before activating a virtual environment. ```plaintext C:\Windows\System32 ``` -------------------------------- ### Review Full Code Example Source: https://github.com/fastapi/sqlmodel/blob/main/docs/tutorial/select.md This code demonstrates creating a database, adding heroes, committing changes, and then selecting heroes from the database using SQLModel. ```python from typing import List, Optional from fastapi import FastAPI from sqlmodel import Field, SQLModel, create_engine, Session, select class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str = Field(index=True) secret_name: str age: Optional[int] = Field(default=None, index=True) def create_db_and_tables(): engine = create_engine("sqlite:///database.db") SQLModel.metadata.create_all(engine) def create_heroes(): engine = create_engine("sqlite:///database.db") with Session(engine) as session: hero_1 = Hero(name="Deadpond", secret_name="Dive Wilson", age=30) hero_2 = Hero(name="Spider-Boy", secret_name="Pedro Parqueador", age=16) hero_3 = Hero(name="Rusty-Man", secret_name="Tommy Sharp", age=48) session.add(hero_1) session.add(hero_2) session.add(hero_3) session.commit() def select_heroes(*, session: Session): statement = select(Hero) results = session.exec(statement) for hero in results: print(hero) def main(): create_db_and_tables() create_heroes() engine = create_engine("sqlite:///database.db") with Session(engine) as session: select_heroes(session=session) if __name__ == "__main__": main() ``` -------------------------------- ### Install packages from requirements.txt with pip Source: https://github.com/fastapi/sqlmodel/blob/main/docs/virtual-environments.md Use this command to install all packages listed in your requirements.txt file using pip. ```console $ pip install -r requirements.txt ---> 100% ``` -------------------------------- ### Full Delete Example (Python 3.10+) Source: https://github.com/fastapi/sqlmodel/blob/main/docs/tutorial/delete.md This Python code demonstrates the complete process of deleting a hero from the database using SQLModel. It includes creating a hero, querying for it, deleting it, and confirming the deletion. Ensure you have the necessary imports and session setup. ```python from typing import Optional from sqlmodel import Field, SQLModel, create_engine, Session, select class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str = Field(index=True) secret_name: str age: Optional[int] = Field(default=None, index=True) engine = create_engine("sqlite:///database.db") def create_db_and_tables(): SQLModel.metadata.create_all(engine) def create_heroes(): hero_1 = Hero(name="Deadpond", secret_name="Dive Wilson") hero_2 = Hero(name="Spider-Boy", secret_name="Pedro Parqueador") hero_3 = Hero(name="Rusty-Man", secret_name="Tommy Sharp", age=48) with Session(engine) as session: session.add(hero_1) session.add(hero_2) session.add(hero_3) session.commit() session.refresh(hero_1) session.refresh(hero_2) session.refresh(hero_3) print("Created heroes:", hero_1, hero_2, hero_3) def select_heroes(): with Session(engine) as session: statement = select(Hero) results = session.exec(statement) for hero in results: print(hero) def delete_hero(): with Session(engine) as session: statement = select(Hero).where(Hero.name == "Spider-Boy") results = session.exec(statement) hero = results.first() if hero: print("Deleting hero:", hero) session.delete(hero) session.commit() session.refresh(hero) print("Deleted hero:", hero) else: print("Hero not found") def main(): create_db_and_tables() create_heroes() select_heroes() delete_hero() select_heroes() if __name__ == "__main__": main() ``` -------------------------------- ### Example PATH before activation (Linux/macOS) Source: https://github.com/fastapi/sqlmodel/blob/main/docs/virtual-environments.md Illustrates a typical PATH environment variable on Linux or macOS before activating a virtual environment. ```plaintext /usr/bin:/bin:/usr/sbin:/sbin ``` -------------------------------- ### Application Setup and Execution Source: https://github.com/fastapi/sqlmodel/blob/main/docs/tutorial/code-structure.md This snippet demonstrates how to create a FastAPI application, set up the database, and define a root endpoint. It imports models and database functions from other modules. ```python from fastapi import FastAPI from .database import create_db_and_tables, engine from .models import Hero def create_app(): create_db_and_tables() app = FastAPI(title="My API") @app.get("/") def read_root(): return {"Hello": "World"} return app app = create_app() def main(): hero = Hero(name="Deadpond", secret_name="Dive Wilson") team = Team(name="Z-Force", headquarters="Sister Margaret's Bar") hero.team = team with Session(engine) as session: session.add(hero) session.add(team) session.commit() session.refresh(hero) session.refresh(team) print("Created hero:", hero) print("Hero's team:", hero.team) if __name__ == "__main__": main() ``` -------------------------------- ### Install Testing Dependencies Source: https://github.com/fastapi/sqlmodel/blob/main/docs/tutorial/fastapi/tests.md Install the 'requests' and 'pytest' libraries required for testing FastAPI applications. Ensure your virtual environment is activated before running this command. ```console pip install requests pytest ``` -------------------------------- ### Create Sample Data for Examples Source: https://github.com/fastapi/sqlmodel/blob/main/docs/tutorial/limit-and-offset.md This code sets up a list of hero objects to be used in subsequent database operations. Ensure you have a database session and Hero model defined. ```python from typing import List, Optional from sqlmodel import Field, SQLModel class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str = Field(index=True) secret_name: str age: Optional[int] = Field(default=None, index=True) def create_heroes(): hero_1 = Hero(name="Deadpond", secret_name="Dive Wilson") hero_2 = Hero(name="Spider-Boy", secret_name="Pedro Parqueador") hero_3 = Hero(name="Rusty-Man", secret_name="Tommy Sharp", age=48) hero_4 = Hero(name="Spider-Girl", secret_name="Natalia Roman-on", age=32) hero_5 = Hero(name="Black Lion", secret_name="Trevor Challa", age=35) hero_6 = Hero(name="Dr. Weird", secret_name="Steve Weird", age=36) hero_7 = Hero(name="Captain North", secret_name="Esther Hanna", age=35) return [hero_1, hero_2, hero_3, hero_4, hero_5, hero_6, hero_7] ``` -------------------------------- ### Run Program with LIMIT, OFFSET, and WHERE on Command Line Source: https://github.com/fastapi/sqlmodel/blob/main/docs/tutorial/limit-and-offset.md Shows how to execute a query with WHERE, LIMIT, and OFFSET clauses from the command line. This example filters heroes by age and then paginates the results. ```console $ python app.py // Previous output omitted 🙈 // Select with WHERE and LIMIT and OFFSET INFO Engine SELECT hero.id, hero.name, hero.secret_name, hero.age FROM hero WHERE hero.age > ? LIMIT ? OFFSET ? INFO Engine [no key 0.00022s] (32, 2, 1) // Print the heroes received, only 2 [ Hero(age=36, id=6, name='Dr. Weird', secret_name='Steve Weird'), Hero(age=48, id=3, name='Rusty-Man', secret_name='Tommy Sharp') ] ``` -------------------------------- ### Install SQLModel with Pip Source: https://github.com/fastapi/sqlmodel/blob/main/docs/install.md Use this command to install SQLModel and its core dependencies (Pydantic and SQLAlchemy). ```console $ pip install sqlmodel ---> 100% Successfully installed sqlmodel pydantic sqlalchemy ``` -------------------------------- ### SQLModel Data Creation for Filtering Examples Source: https://github.com/fastapi/sqlmodel/blob/main/docs/tutorial/where.md Adds multiple hero records to the database, including varying ages, to facilitate clearer examples for comparison operators. ```python hero_1 = Hero(name='Deadpond', secret_name='Dive Wilson') hero_2 = Hero(name='Spider-Boy', secret_name='Pedro Parqueador') hero_3 = Hero(name='Rusty-Man', secret_name='Tommy Sharp', age=48) hero_4 = Hero(name='Spider-Girl', secret_name='Jane Wilson', age=16) hero_5 = Hero(name='Black Lion', secret_name='Trevor Challa', age=35) hero_6 = Hero(name='Dr. Weird', secret_name='Steve Weird', age=36) hero_7 = Hero(name='Captain North America', secret_name='Esteban Rogelios', age=93) session.add(hero_1) session.add(hero_2) session.add(hero_3) session.add(hero_4) session.add(hero_5) session.add(hero_6) session.add(hero_7) session.commit() ``` -------------------------------- ### Create FastAPI App Instance Source: https://github.com/fastapi/sqlmodel/blob/main/docs/tutorial/fastapi/simple-hero-api.md Import the FastAPI class and create an app instance. This is the basic setup for any FastAPI application. ```python from fastapi import FastAPI app = FastAPI() ``` -------------------------------- ### Select Data with SQLModel Source: https://github.com/fastapi/sqlmodel/blob/main/docs/tutorial/where.md Example of a basic select statement in SQLModel. ```Python statement = select(Hero) with Session(engine) as session: results = session.exec(statement) for hero in results: print(hero) ``` -------------------------------- ### Example PATH after activation (Windows) Source: https://github.com/fastapi/sqlmodel/blob/main/docs/virtual-environments.md Shows how the PATH environment variable is modified after activating a virtual environment on Windows, prioritizing the virtual environment's Scripts directory. ```plaintext C:\Users\user\code\awesome-project\.venv\Scripts;C:\Windows\System32 ``` -------------------------------- ### Importing Engine and SQLModel from db.py Source: https://github.com/fastapi/sqlmodel/blob/main/docs/tutorial/create-db-and-table.md This example demonstrates importing the engine and SQLModel from a separate db.py file in app.py. This approach ensures that models are registered before create_all() is called. ```python # app.py from .db import engine, SQLModel SQLModel.metadata.create_all(engine) ``` -------------------------------- ### Correct Order for Table Creation Source: https://github.com/fastapi/sqlmodel/blob/main/docs/tutorial/create-db-and-table.md This example shows the correct way to call create_all() by importing the models before the function call. This ensures that all model classes are registered in SQLModel.metadata. ```python from sqlmodel import SQLModel from . import models from .db import engine SQLModel.metadata.create_all(engine) ``` -------------------------------- ### Example PATH after activation (Linux/macOS) Source: https://github.com/fastapi/sqlmodel/blob/main/docs/virtual-environments.md Shows how the PATH environment variable is modified after activating a virtual environment on Linux or macOS, prioritizing the virtual environment's bin directory. ```plaintext /home/user/code/awesome-project/.venv/bin:/usr/bin:/bin:/usr/sbin:/sbin ``` -------------------------------- ### Example Windows PATH Variable Source: https://github.com/fastapi/sqlmodel/blob/main/docs/environment-variables.md Shows the directory structure of a typical PATH environment variable on Windows systems, using semicolons as separators. ```plaintext C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32 ``` -------------------------------- ### Running a Multi-File Python Project Source: https://github.com/fastapi/sqlmodel/blob/main/docs/tutorial/code-structure.md This example shows the command-line instruction to execute a Python application structured as a package. It uses the '-m' flag to run a module within the package. ```console python -m project.app ``` -------------------------------- ### Select from Database Source: https://github.com/fastapi/sqlmodel/blob/main/docs/index.md Query a database for specific records using SQLModel's select statement. This example retrieves a hero by name. ```Python from sqlmodel import Field, Session, SQLModel, create_engine, select class Hero(SQLModel, table=True): id: int | None = Field(default=None, primary_key=True) name: str secret_name: str age: int | None = None engine = create_engine("sqlite:///database.db") with Session(engine) as session: statement = select(Hero).where(Hero.name == "Spider-Boy") hero = session.exec(statement).first() print(hero) ``` -------------------------------- ### Updated Windows PATH with Custom Python Source: https://github.com/fastapi/sqlmodel/blob/main/docs/environment-variables.md Illustrates the addition of a custom Python installation path to the PATH environment variable on Windows. ```plaintext C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32;C:\opt\custompython\bin ``` -------------------------------- ### Console Output: Cascade Delete Example Source: https://github.com/fastapi/sqlmodel/blob/main/docs/tutorial/relationship-attributes/cascade-delete-relationships.md Demonstrates the output when deleting heroes before deleting a team, showing the `ON DELETE RESTRICT` behavior and manual disassociation. ```console $ python app.py // Some boilerplate and previous output omitted 😉 // The hero table is created with the ON DELETE RESTRICT CREATE TABLE hero ( id INTEGER NOT NULL, name VARCHAR NOT NULL, secret_name VARCHAR NOT NULL, age INTEGER, team_id INTEGER, PRIMARY KEY (id), FOREIGN KEY(team_id) REFERENCES team (id) ON DELETE RESTRICT ) // We manually disassociate the heroes from the team INFO Engine UPDATE hero SET team_id=? WHERE hero.id = ? INFO Engine [generated in 0.00008s] [(None, 4), (None, 5)] // We print the team from which we removed heroes Team with removed heroes: name='Wakaland' id=3 headquarters='Wakaland Capital City' // Now we can delete the team INFO Engine DELETE FROM team WHERE team.id = ? INFO Engine [generated in 0.00008s] (3,) INFO Engine COMMIT Deleted team: name='Wakaland' id=3 headquarters='Wakaland Capital City' // The heroes Black Lion and Princess Sure-E are no longer associated with the team Black Lion has no team: secret_name='Trevor Challa' name='Black Lion' team_id=None age=35 id=4 Princess Sure-E has no team: secret_name='Sure-E' name='Princess Sure-E' team_id=None age=None id=5 ``` -------------------------------- ### Example Linux/macOS PATH Variable Source: https://github.com/fastapi/sqlmodel/blob/main/docs/environment-variables.md Illustrates the directory structure of a typical PATH environment variable on Linux or macOS systems, used for program lookup. ```plaintext /usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin ``` -------------------------------- ### Activate New Virtual Environment (Linux/macOS) Source: https://github.com/fastapi/sqlmodel/blob/main/docs/virtual-environments.md Activate the virtual environment for the current project using the 'source' command. This ensures that the correct Python interpreter and installed packages are used. ```bash $ source .venv/bin/activate ``` -------------------------------- ### Complete SQLModel Application for Data Insertion Source: https://github.com/fastapi/sqlmodel/blob/main/docs/tutorial/insert.md A full Python script demonstrating SQLModel setup, including model definition, engine creation, database initialization, and data insertion using a 'with' block for session management. This code can be saved as 'app.py' and executed. ```python from typing import List from fastapi import FastAPI from sqlmodel import Field, SQLModel, create_engine, Session class Hero(SQLModel, table=True): id: int | None = Field(default=None, primary_key=True) name: str = Field(index=True) secret_name: str age: int | None = Field(default=None, index=True) engine = create_engine("sqlite:///database.db") def create_db_and_tables(): SQLModel.metadata.create_all(engine) def create_heroes(): hero_1 = Hero(name="Deadpond", secret_name="Dive Wilson") hero_2 = Hero(name="Spider-Boy", secret_name="Pedro Parqueador") hero_3 = Hero(name="Rusty-Man", secret_name="Tommy Sharp", age=48) with Session(engine) as session: session.add(hero_1) session.add(hero_2) session.add(hero_3) session.commit() session.refresh(hero_1) session.refresh(hero_2) session.refresh(hero_3) print("Created heroes:") print(f"- {hero_1}") print(f"- {hero_2}") print(f"- {hero_3}") def main(): create_db_and_tables() create_heroes() if __name__ == "__main__": main() ``` -------------------------------- ### Select All Heroes (Previous Example) Source: https://github.com/fastapi/sqlmodel/blob/main/docs/tutorial/limit-and-offset.md This is the standard method to select all records from the hero table without any filtering or limiting. It's shown for comparison with limited selections. ```python from sqlmodel import select statement = select(Hero) heroes = session.exec(statement) for hero in heroes: print(hero) ``` -------------------------------- ### Nullable Field Example Source: https://github.com/fastapi/sqlmodel/blob/main/docs/tutorial/create-db-and-table.md Demonstrates how to define a field that can be either an integer or None, making the corresponding database column nullable and setting None as the default value. ```Python age: Optional[int] = Field(default=None, index=True) ``` -------------------------------- ### Order of Operations for Table Creation Source: https://github.com/fastapi/sqlmodel/blob/main/docs/tutorial/create-db-and-table.md This example demonstrates the incorrect way to call create_all() without importing the models first, which would result in an empty metadata object. Always import models before calling create_all(). ```python # This wouldn't work! from sqlmodel import SQLModel from .db import engine SQLModel.metadata.create_all(engine) ``` -------------------------------- ### Add More Tests for FastAPI SQLModel Source: https://github.com/fastapi/sqlmodel/blob/main/docs/tutorial/fastapi/tests.md Add tests for invalid data, errors, and corner cases. These tests require the 'client' fixture to get the TestClient with database setup. ```python def test_create_hero_invalid_json(): response = client.post("/heroes/", json={"name": "Deadpond", "secret_name": "Dive Wilson"}) assert response.status_code == 422 def test_create_hero_invalid_schema(): response = client.post("/heroes/", json={"name": "Spider-Boy", "secret_name": "Pedro Parqueador", "age": 16}) assert response.status_code == 422 def test_create_hero_valid_json(): response = client.post("/heroes/", json={"name": "Spider-Boy", "secret_name": "Pedro Parqueador"}) assert response.status_code == 200 assert response.json()["name"] == "Spider-Boy" assert response.json()["secret_name"] == "Pedro Parqueador" assert response.json()["age"] == None def test_read_heroes_correctly(): response = client.get("/heroes/") assert response.status_code == 200 assert response.json() == [] def test_create_hero_and_read_it(): response = client.post("/heroes/", json={"name": "Deadpond", "secret_name": "Dive Wilson"}) assert response.status_code == 200 create_hero_resp_json = response.json() assert create_hero_resp_json["name"] == "Deadpond" assert create_hero_resp_json["secret_name"] == "Dive Wilson" assert create_hero_resp_json["age"] == None response = client.get("/heroes/") assert response.status_code == 200 assert response.json() == [ { "name": "Deadpond", "secret_name": "Dive Wilson", "age": None, } ] def test_create_multiple_heroes_and_read_them(): response = client.post("/heroes/", json={"name": "Dr. Weird", "secret_name": "Steve Weird"}) assert response.status_code == 200 response = client.post("/heroes/", json={"name": "Captain Amazing", "secret_name": "Jonny Storm"}) assert response.status_code == 200 response = client.post("/heroes/", json={"name": "The Amazing Spiderman", "secret_name": "Peter Parker"}) assert response.status_code == 200 response = client.get("/heroes/") assert response.status_code == 200 assert len(response.json()) == 3 ``` -------------------------------- ### Install Newer Package Version Source: https://github.com/fastapi/sqlmodel/blob/main/docs/virtual-environments.md Install a newer version of a package, like 'harry' version 3, into your current Python environment. This command will typically replace any previously installed version of the same package. ```bash $ pip install "harry==3" ``` -------------------------------- ### Create Database Engine and Tables Source: https://github.com/fastapi/sqlmodel/blob/main/docs/tutorial/connect/create-connected-tables.md Set up the database engine and create all defined tables in the database. This function should be called to initialize the database schema. ```python from sqlmodel import SQLModel, create_engine engine = create_engine("sqlite:///database.db") def create_db_and_tables(): SQLModel.metadata.create_all(engine) ``` -------------------------------- ### Create Instances with Fields (Legacy Approach) Source: https://github.com/fastapi/sqlmodel/blob/main/docs/tutorial/relationship-attributes/create-and-update-relationships.md Demonstrates the manual approach of creating instances, committing to generate IDs, and then using those IDs to link related records. ```python team_preventers = Team(name="Preventers", headquarters="Sharp Tower") team_z_force = Team(name="Z-Force", headquarters="Sister Margaret's Bar") session.add(team_preventers) session.add(team_z_force) session.commit() hero_deadpond = Hero( name="Deadpond", secret_name="Dive Wilson", team_id=team_preventers.id ) hero_rusty_man = Hero( name="Rusty-Man", secret_name="Tommy Sharp", team_id=team_preventers.id ) hero_spider_boy = Hero( name="Spider-Boy", secret_name="Pedro Parqueador", team_id=team_z_force.id ) session.add(hero_deadpond) session.add(hero_rusty_man) session.add(hero_spider_boy) session.commit() ``` -------------------------------- ### Malicious SQL Injection Example Source: https://github.com/fastapi/sqlmodel/blob/main/docs/db-to-code.md An example of a malicious input string designed to exploit SQL injection vulnerabilities by appending a destructive SQL command. ```SQL 2; DROP TABLE hero ``` -------------------------------- ### Create Project Directory Structure Source: https://github.com/fastapi/sqlmodel/blob/main/docs/virtual-environments.md Commands to create a new project directory and navigate into it. ```console $ cd $ mkdir code $ cd code $ mkdir awesome-project $ cd awesome-project ``` -------------------------------- ### Create Database Tables Source: https://github.com/fastapi/sqlmodel/blob/main/docs/tutorial/many-to-many/create-models-with-link.md Initialize the database engine and create all defined tables. ```python def create_db_and_tables(): SQLModel.metadata.create_all(engine) def main(): create_db_and_tables() ``` -------------------------------- ### Get dictionary excluding unset fields Source: https://github.com/fastapi/sqlmodel/blob/main/docs/tutorial/fastapi/update.md Shows how to use `model_dump(exclude_unset=True)` to get a dictionary of data that only includes fields explicitly sent by the client, even if they are null. ```Python { "age": None } ``` -------------------------------- ### Get Updated Hero Data Source: https://github.com/fastapi/sqlmodel/blob/main/docs/tutorial/fastapi/update.md Use `model_dump(exclude_unset=True)` to get a dictionary containing only the fields that were actually sent by the client, preventing accidental overwrites with default values. ```python hero_data = hero_update.model_dump(exclude_unset=True) ``` -------------------------------- ### Install Specific Package Version Source: https://github.com/fastapi/sqlmodel/blob/main/docs/virtual-environments.md Install a specific version of a package, like 'harry' version 1, into your current Python environment. This is often done within a virtual environment to isolate dependencies. ```bash $ pip install "harry==1" ``` -------------------------------- ### Create Database and Table Source: https://github.com/fastapi/sqlmodel/blob/main/docs/tutorial/insert.md This Python code sets up the database and the 'hero' table using SQLModel. It's a prerequisite for inserting data. ```python from typing import Optional from sqlmodel import Field, SQLModel class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str = Field(index=True) secret_name: str age: Optional[int] = Field(default=None, index=True) def create_db_and_tables(): SQLModel.metadata.create_all(engine) ``` -------------------------------- ### Run Program with Last Batch using LIMIT and OFFSET Source: https://github.com/fastapi/sqlmodel/blob/main/docs/tutorial/limit-and-offset.md Demonstrates how to retrieve the last batch of heroes from the database using LIMIT and OFFSET on the command line. Shows the SQL query executed and the resulting output. ```console $ python app.py // Previous output omitted 🙈 // Select last batch with LIMIT and OFFSET INFO Engine SELECT hero.id, hero.name, hero.secret_name, hero.age FROM hero LIMIT ? OFFSET ? INFO Engine [no key 0.00038s] (3, 6) // Print last batch of heroes, only one [ Hero(age=93, secret_name='Esteban Rogelios', id=7, name='Captain North America') ] ``` -------------------------------- ### Complex Relationship Configuration Source: https://github.com/fastapi/sqlmodel/blob/main/docs/tutorial/relationship-attributes/back-populates.md Example of a model with multiple relationship attributes using back_populates. ```python class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str = Field(index=True) secret_name: str age: Optional[int] = None team_id: Optional[int] = Field(default=None, foreign_key="team.id") team: Optional[Team] = Relationship(back_populates="heroes") weapon_id: Optional[int] = Field(default=None, foreign_key="weapon.id") weapon: Optional["Weapon"] = Relationship(back_populates="hero") ``` -------------------------------- ### Refresh First Hero Source: https://github.com/fastapi/sqlmodel/blob/main/docs_src/tutorial/update/annotations/en/tutorial004.md Refreshes the first hero object from the database, starting a new transaction. ```text INFO Engine BEGIN (implicit) INFO Engine SELECT hero.id, hero.name, hero.secret_name, hero.age FROM hero WHERE hero.id = ? INFO Engine [generated in 0.00023s] (2,) ``` -------------------------------- ### Run Python App to Create DB and Table Source: https://github.com/fastapi/sqlmodel/blob/main/docs/tutorial/create-db-and-table.md Execute this Python script to create the database and table. Ensure your virtual environment is activated. The output will show the generated SQL. ```python from typing import List, Optional from sqlmodel import Field, SQLModel, create_engine class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str = Field(index=True) secret_name: str age: Optional[int] = Field(default=None, index=True) hero_db = "hero.db" engine = create_engine(f"sqlite:///{hero_db}") def create_db_and_tables(): SQLModel.metadata.create_all(engine) def main(): create_db_and_tables() if __name__ == "__main__": main() ``` -------------------------------- ### Select Second Hero Source: https://github.com/fastapi/sqlmodel/blob/main/docs_src/tutorial/update/annotations/en/tutorial004.md Executes a SELECT statement for a second hero, triggering an implicit transaction start. ```text INFO Engine BEGIN (implicit) INFO Engine SELECT hero.id, hero.name, hero.secret_name, hero.age FROM hero WHERE hero.name = ? INFO Engine [no key 0.00020s] ('Captain North America',) ``` -------------------------------- ### Get List of Relationship Objects Source: https://github.com/fastapi/sqlmodel/blob/main/docs/tutorial/relationship-attributes/read-relationships.md Retrieves a list of related objects on the many-side of a one-to-many relationship by accessing the attribute. ```python def select_heroes(): with Session(engine) as session: statement = select(Team).where(Team.name == "Preventers") results = session.exec(statement) team = results.first() print("Preventers heroes:", team.heroes) ``` -------------------------------- ### Updated Linux/macOS PATH with Custom Python Source: https://github.com/fastapi/sqlmodel/blob/main/docs/environment-variables.md Demonstrates how a custom Python installation directory is appended to the PATH variable on Linux/macOS. ```plaintext /usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/custompython/bin ``` -------------------------------- ### Create and Use Env Vars in Shell Source: https://github.com/fastapi/sqlmodel/blob/main/docs/environment-variables.md Demonstrates how to create and use environment variables directly in the terminal. This is useful for setting up configurations before running applications. ```bash $ export MY_NAME="Wade Wilson" $ echo "Hello $MY_NAME" ``` ```powershell $Env:MY_NAME = "Wade Wilson" $echo "Hello $Env:MY_NAME" ``` -------------------------------- ### Create Database and Table Source: https://github.com/fastapi/sqlmodel/blob/main/docs/tutorial/create-db-and-table.md This is the primary step to create the database file and the table within it. Ensure the engine is created before calling this. ```python SQLModel.metadata.create_all(engine) ``` -------------------------------- ### Explicitly Refresh Hero 2 Source: https://github.com/fastapi/sqlmodel/blob/main/docs_src/tutorial/automatic_id_none_refresh/annotations/en/tutorial002.md Explicitly refreshes the Hero 2 object, executing SQL to get the latest data from the database. ```text INFO Engine SELECT hero.id, hero.name, hero.secret_name, hero.age FROM hero WHERE hero.id = ? INFO Engine [cached since 0.001487s ago] (2,) ``` -------------------------------- ### Main function to create DB and tables Source: https://github.com/fastapi/sqlmodel/blob/main/docs/tutorial/connect/create-connected-tables.md The main function to execute the database and table creation process. This is the entry point for initializing the application's database. ```python def main(): create_db_and_tables() if __name__ == "__main__": main() ``` -------------------------------- ### Get All Heroes as a List Source: https://github.com/fastapi/sqlmodel/blob/main/docs/tutorial/select.md Use the `results.all()` method to retrieve all matching objects as a list. This is useful for returning data from web APIs. ```python heroes = session.exec(select(Hero)).all() print(heroes) ``` -------------------------------- ### Create a Team with Heroes Source: https://github.com/fastapi/sqlmodel/blob/main/docs/tutorial/relationship-attributes/create-and-update-relationships.md Demonstrates creating a Team and passing a list of Hero instances to the heroes argument. ```python hero_black_lion = Hero(name="Black Lion", secret_name="Trevor Challa") hero_princess_sure_e = Hero(name="Princess Sure-E", secret_name="Shuri") team_wakanda = Team( name="Wakanda", headquarters="Wakanda", heroes=[hero_black_lion, hero_princess_sure_e], ) session.add(team_wakanda) session.commit() ``` -------------------------------- ### Run Project Script After Activation Source: https://github.com/fastapi/sqlmodel/blob/main/docs/virtual-environments.md Execute your project's main script using the Python interpreter from the newly activated virtual environment. This confirms that dependencies are correctly resolved. ```bash $ python main.py I solemnly swear 🐺 ``` -------------------------------- ### Get Relationship Team (New Way) Source: https://github.com/fastapi/sqlmodel/blob/main/docs/tutorial/relationship-attributes/read-relationships.md Accesses the team directly via the relationship attribute, allowing automatic database fetching. ```python def select_heroes(): with Session(engine) as session: statement = select(Hero).where(Hero.name == "Deadpond") results = session.exec(statement) hero = results.first() print("Hero team:", hero.team) ``` -------------------------------- ### Navigate to Project Directory Source: https://github.com/fastapi/sqlmodel/blob/main/docs/virtual-environments.md Change the current directory to your project's root folder. This is a common first step before activating a project-specific virtual environment. ```bash $ cd ~/code/prisoner-of-azkaban ``` -------------------------------- ### SQL Command to Drop an Index Source: https://github.com/fastapi/sqlmodel/blob/main/docs/release-notes.md This SQL code provides examples of how to manually drop an unnecessary index, like 'ix_hero_secret_name', from a database table. ```SQL DROP INDEX ix_hero_secret_name ``` ```SQL DROP INDEX ix_hero_secret_name ON hero; ``` -------------------------------- ### Filter Data with SQL WHERE Clause Source: https://github.com/fastapi/sqlmodel/blob/main/docs/tutorial/where.md Use the WHERE clause in SQL to specify conditions for selecting rows. This example filters for heroes where the name is 'Deadpond'. ```sql SELECT id, name, secret_name, age FROM hero WHERE name = "Deadpond" ``` -------------------------------- ### Print Updated Hero Object Source: https://github.com/fastapi/sqlmodel/blob/main/docs/tutorial/update.md After updating an object, you can print it to verify the changes. This example shows the hero object with its newly updated age. ```python hero = await session.get(Hero, hero_id) if not hero: print(f"Hero with id {hero_id} not found") return hero.age = 16 session.add(hero) await session.commit() await session.refresh(hero) print(f"Updated hero: {hero}") ``` -------------------------------- ### Create a SQLModel Instance Source: https://github.com/fastapi/sqlmodel/blob/main/docs/tutorial/where.md Instantiate a SQLModel object with provided values. ```Python hero = Hero(name="Deadpond", secret_name="Dive Wilson") ``` -------------------------------- ### Python Mapping Function Example Source: https://github.com/fastapi/sqlmodel/blob/main/docs/db-to-code.md A simple Python function that maps a string of lowercase letters to uppercase. This illustrates the 'Mapper' concept in ORMs. ```Python def map_lower_to_upper(value: str): return value.upper() ``` -------------------------------- ### Run FastAPI Server in Production Source: https://github.com/fastapi/sqlmodel/blob/main/docs/tutorial/fastapi/simple-hero-api.md Use `fastapi run` for production deployments instead of `fastapi dev` to avoid unnecessary resource consumption and potential errors. ```console $ fastapi run main.py INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit) ``` -------------------------------- ### Create Database Engine Source: https://github.com/fastapi/sqlmodel/blob/main/docs_src/tutorial/create_db_and_table/annotations/en/tutorial003.md Sets up the database URL for SQLite and creates an engine to manage database connections. This step does not create the database file or tables. ```python from sqlmodel import create_engine DATABASE_FILE = "database.db" DATABASE_CONNECTION_STRING = f"sqlite:///{DATABASE_FILE}" engine = create_engine(DATABASE_CONNECTION_STRING, echo=True) ``` -------------------------------- ### Define Update Heroes Function Source: https://github.com/fastapi/sqlmodel/blob/main/docs/tutorial/many-to-many/update-remove-relationships.md Define a function to retrieve specific heroes and teams for updating many-to-many relationships. This example uses `select()` for data retrieval. ```python def update_heroes(): statement = select(Hero, Team) hero_spider_boy = session.exec(statement).first() team_z_force = session.exec(statement).last() ``` -------------------------------- ### Create Virtual Environment with uv Source: https://github.com/fastapi/sqlmodel/blob/main/docs/virtual-environments.md Use the `uv` tool to create a virtual environment. By default, it creates a directory named `.venv`. ```console uv venv ``` -------------------------------- ### Activate Virtual Environment on Linux/macOS Source: https://github.com/fastapi/sqlmodel/blob/main/docs/virtual-environments.md Use this command in your terminal to activate the virtual environment on Linux or macOS. Do this every time you start a new terminal session. ```bash source .venv/bin/activate ``` -------------------------------- ### Select by Primary Key with .get() Source: https://github.com/fastapi/sqlmodel/blob/main/docs/tutorial/one.md Uses the session.get() shortcut to fetch a record by its primary key efficiently. ```python hero = session.get(Hero, 1) print("Hero:", hero) ```