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

44 statements  

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

1from typing import Optional 1abcd

2 

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

4 

5 

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

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

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

9 ) 

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

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

12 ) 

13 

14 

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

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

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

18 headquarters: str 1abcd

19 

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

21 

22 

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

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

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

26 secret_name: str 1abcd

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

28 

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

30 

31 

32sqlite_file_name = "database.db" 1abcd

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

34 

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

36 

37 

38def create_db_and_tables(): 1abcd

39 SQLModel.metadata.create_all(engine) 1abcd

40 

41 

42def create_heroes(): 1abcd

43 with Session(engine) as session: 1abcd

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

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

46 

47 hero_deadpond = Hero( 1abcd

48 name="Deadpond", 

49 secret_name="Dive Wilson", 

50 teams=[team_z_force, team_preventers], 

51 ) 

52 hero_rusty_man = Hero( 1abcd

53 name="Rusty-Man", 

54 secret_name="Tommy Sharp", 

55 age=48, 

56 teams=[team_preventers], 

57 ) 

58 hero_spider_boy = Hero( 1abcd

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

60 ) 

61 session.add(hero_deadpond) 1abcd

62 session.add(hero_rusty_man) 1abcd

63 session.add(hero_spider_boy) 1abcd

64 session.commit() 1abcd

65 

66 session.refresh(hero_deadpond) 1abcd

67 session.refresh(hero_rusty_man) 1abcd

68 session.refresh(hero_spider_boy) 1abcd

69 

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

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

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

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

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

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

76 

77 

78def main(): 1abcd

79 create_db_and_tables() 1abcd

80 create_heroes() 1abcd

81 

82 

83if __name__ == "__main__": 1abcd

84 main()