Coverage for docs_src/advanced/uuid/tutorial002.py: 100%
44 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-16 00:02 +0000
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-16 00:02 +0000
1import uuid 1nopqrstuvwxyz
3from sqlmodel import Field, Session, SQLModel, create_engine 1nopqrstuvwxyz
6class Hero(SQLModel, table=True): 1nopqrstuvwxyz
7 id: uuid.UUID = Field(default_factory=uuid.uuid4, primary_key=True) 1nopqrstuvwxyz
8 name: str = Field(index=True) 1nopqrstuvwxyz
9 secret_name: str 1nopqrstuvwxyz
10 age: int | None = Field(default=None, index=True) 1nopqrstuvwxyz
13sqlite_file_name = "database.db" 1nopqrstuvwxyz
14sqlite_url = f"sqlite:///{sqlite_file_name}" 1nopqrstuvwxyz
16engine = create_engine(sqlite_url, echo=True) 1nopqrstuvwxyz
19def create_db_and_tables(): 1nopqrstuvwxyz
20 SQLModel.metadata.create_all(engine) 1abcdefghijklm
23def create_hero(): 1nopqrstuvwxyz
24 with Session(engine) as session: 1abcdefghijklm
25 hero = Hero(name="Deadpond", secret_name="Dive Wilson") 1abcdefghijklm
26 print("The hero before saving in the DB") 1abcdefghijklm
27 print(hero) 1abcdefghijklm
28 print("The hero ID was already set") 1abcdefghijklm
29 print(hero.id) 1abcdefghijklm
30 session.add(hero) 1abcdefghijklm
31 session.commit() 1abcdefghijklm
32 session.refresh(hero) 1abcdefghijklm
33 print("After saving in the DB") 1abcdefghijklm
34 print(hero) 1abcdefghijklm
37def select_hero(): 1nopqrstuvwxyz
38 with Session(engine) as session: 1abcdefghijklm
39 hero_2 = Hero(name="Spider-Boy", secret_name="Pedro Parqueador") 1abcdefghijklm
40 session.add(hero_2) 1abcdefghijklm
41 session.commit() 1abcdefghijklm
42 session.refresh(hero_2) 1abcdefghijklm
43 hero_id = hero_2.id 1abcdefghijklm
44 print("Created hero:") 1abcdefghijklm
45 print(hero_2) 1abcdefghijklm
46 print("Created hero ID:") 1abcdefghijklm
47 print(hero_id) 1abcdefghijklm
49 selected_hero = session.get(Hero, hero_id) 1abcdefghijklm
50 print("Selected hero:") 1abcdefghijklm
51 print(selected_hero) 1abcdefghijklm
52 print("Selected hero ID:") 1abcdefghijklm
53 print(selected_hero.id) 1abcdefghijklm
56def main() -> None: 1nopqrstuvwxyz
57 create_db_and_tables() 1abcdefghijklm
58 create_hero() 1abcdefghijklm
59 select_hero() 1abcdefghijklm
62if __name__ == "__main__": 1nopqrstuvwxyz
63 main()