Coverage for docs_src/tutorial/many_to_many/tutorial001.py: 100%

44 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2024-09-09 00:02 +0000

1from typing import List, Optional 1abcdef

2 

3from sqlmodel import Field, Relationship, Session, SQLModel, create_engine 1abcdef

4 

5 

6class HeroTeamLink(SQLModel, table=True): 1abcdef

7 team_id: Optional[int] = Field( 1abcdef

8 default=None, foreign_key="team.id", primary_key=True 

9 ) 

10 hero_id: Optional[int] = Field( 1abcdef

11 default=None, foreign_key="hero.id", primary_key=True 

12 ) 

13 

14 

15class Team(SQLModel, table=True): 1abcdef

16 id: Optional[int] = Field(default=None, primary_key=True) 1abcdef

17 name: str = Field(index=True) 1abcdef

18 headquarters: str 1abcdef

19 

20 heroes: List["Hero"] = Relationship(back_populates="teams", link_model=HeroTeamLink) 1abcdef

21 

22 

23class Hero(SQLModel, table=True): 1abcdef

24 id: Optional[int] = Field(default=None, primary_key=True) 1abcdef

25 name: str = Field(index=True) 1abcdef

26 secret_name: str 1abcdef

27 age: Optional[int] = Field(default=None, index=True) 1abcdef

28 

29 teams: List[Team] = Relationship(back_populates="heroes", link_model=HeroTeamLink) 1abcdef

30 

31 

32sqlite_file_name = "database.db" 1abcdef

33sqlite_url = f"sqlite:///{sqlite_file_name}" 1abcdef

34 

35engine = create_engine(sqlite_url, echo=True) 1abcdef

36 

37 

38def create_db_and_tables(): 1abcdef

39 SQLModel.metadata.create_all(engine) 1abcdef

40 

41 

42def create_heroes(): 1abcdef

43 with Session(engine) as session: 1abcdef

44 team_preventers = Team(name="Preventers", headquarters="Sharp Tower") 1abcdef

45 team_z_force = Team(name="Z-Force", headquarters="Sister Margaret's Bar") 1abcdef

46 

47 hero_deadpond = Hero( 1abcdef

48 name="Deadpond", 

49 secret_name="Dive Wilson", 

50 teams=[team_z_force, team_preventers], 

51 ) 

52 hero_rusty_man = Hero( 1abcdef

53 name="Rusty-Man", 

54 secret_name="Tommy Sharp", 

55 age=48, 

56 teams=[team_preventers], 

57 ) 

58 hero_spider_boy = Hero( 1abcdef

59 name="Spider-Boy", secret_name="Pedro Parqueador", teams=[team_preventers] 

60 ) 

61 session.add(hero_deadpond) 1abcdef

62 session.add(hero_rusty_man) 1abcdef

63 session.add(hero_spider_boy) 1abcdef

64 session.commit() 1abcdef

65 

66 session.refresh(hero_deadpond) 1abcdef

67 session.refresh(hero_rusty_man) 1abcdef

68 session.refresh(hero_spider_boy) 1abcdef

69 

70 print("Deadpond:", hero_deadpond) 1abcdef

71 print("Deadpond teams:", hero_deadpond.teams) 1abcdef

72 print("Rusty-Man:", hero_rusty_man) 1abcdef

73 print("Rusty-Man Teams:", hero_rusty_man.teams) 1abcdef

74 print("Spider-Boy:", hero_spider_boy) 1abcdef

75 print("Spider-Boy Teams:", hero_spider_boy.teams) 1abcdef

76 

77 

78def main(): 1abcdef

79 create_db_and_tables() 1abcdef

80 create_heroes() 1abcdef

81 

82 

83if __name__ == "__main__": 1abcdef

84 main()